Including modules in the controller

I made a module in the lib directory in the ruby ​​on rails application of it as

module Select def self.included(base) base.extend ClassMethods end module ClassMethods def select_for(object_name, options={}) #does some operation self.send(:include, Selector::InstanceMethods) end end 

I called it in the controller, for example

 include Selector select_for :organization, :submenu => :general 

but I want to call it a function that is

  def select #Call the module here end 
+6
ruby-on-rails
source share
1 answer

Make it clear: you have a method defined in the module and you want this method to be used in the instance method.

 class MyController < ApplicationController include Select # You used to call this in the class scope, we're going to move it to # An instance scope. # # select_for :organization, :submenu => :general def show # Or any action # Now we're using this inside an instance method. # select_for :organization, :submenu => :general end end 

I will change my module a bit. Instead of extend , include used. extend is for adding class methods and include for adding instance methods:

 module Select def self.included(base) base.class_eval do include InstanceMethods end end module InstanceMethods def select_for(object_name, options={}) # Does some operation self.send(:include, Selector::InstanceMethods) end end end 

This will give you an instance method. If you need instance and class methods, you simply add the ClassMethods module and use extend instead of include :

 module Select def self.included(base) base.class_eval do include InstanceMethods extend ClassMethods end end module InstanceMethods def select_for(object_name, options={}) # Does some operation self.send(:include, Selector::InstanceMethods) end end module ClassMethods def a_class_method end end end 

It is clear? In your example, you defined the module as Select , but included Selector in your controller ... I just used Select in my code.

+14
source share

All Articles