让我们澄清一下:您在模块中定义了一个方法,并且您希望在实例方法中使用该方法。
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
我将稍微改变你的模块。这使用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
这将为您提供一个实例方法。如果您想要实例方法和类方法,只需添加 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
这样事情就清楚了吗?在您的示例中,您将模块定义为Select
但包括在内Selector
在你的控制器中......我刚刚用过Select
在我的代码中。