包括控制器中的模块 [英] including Modules in controller
问题描述
我在 ruby on rails 应用程序的 lib 目录中做了一个模块就像
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
推荐答案
让我们澄清一下:您在模块中定义了一个方法,并且您希望在实例方法中使用该方法.
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
我将稍微更改您的模块.这使用 include
而不是 extend
.extend
用于添加类方法,include
用于添加实例方法:
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
那会给你一个实例方法.如果需要实例方法和类方法,只需添加 ClassMethods 模块,并使用 extend
而不是 include
:
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
这能解决问题吗?在您的示例中,您将模块定义为 Select
但在控制器中包含 Selector
...我只是在我的代码中使用了 Select
.
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.
这篇关于包括控制器中的模块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!