views:

99

answers:

1

I have done a module in lib directory in ruby on rails application its like

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 this in a controller like

include Selector

  select_for :organization, :submenu => :general

but I want to call this in a function i.e

 def select
  #Call the module here 
 end
+1  A: 

Hi sgiri,

Welcome to Ruby modules! :-) So first let's clarify: You have a method defined in a module, and you want that method to be used in an 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'm going to change your module slightly. This uses include instead of extend. extend is for adding class methods, and include it 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

That will give you an instance method. If you want both instance and class methods, you just 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

Does that clear things up? In your example you defined a module as Select but included Selector in your controller...I just used Select in my code.

Good luck!

mixonic