包括控制器中的模块

6 ruby-on-rails

我已经在ruby on rails应用程序的lib目录中完成了一个模块

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
Run Code Online (Sandbox Code Playgroud)

我在控制器中称之为

include Selector

  select_for :organization, :submenu => :general
Run Code Online (Sandbox Code Playgroud)

但我想在一个函数中调用它,即

 def select
  #Call the module here 
 end
Run Code Online (Sandbox Code Playgroud)

mix*_*nic 15

让我们澄清一下:您在模块中定义了一个方法,并且希望在实例方法中使用该方法.

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
Run Code Online (Sandbox Code Playgroud)

我要稍微改变你的模块.这用来include代替extend. extend用于添加类方法,include它用于添加实例方法:

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
Run Code Online (Sandbox Code Playgroud)

这将为您提供一个实例方法.如果您想要实例和类方法,只需添加ClassMethods模块,并使用extend而不是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
Run Code Online (Sandbox Code Playgroud)

那清楚了吗?在您的示例中,您将模块定义为Select但包含Selector在控制器中...我只是Select在我的代码中使用.