Rob*_*bin 17 ruby-on-rails activesupport ruby-on-rails-3 ruby-on-rails-3.2
通过良好的语法,可以轻松地为类添加功能.
无论如何,在Rails 3.2中,不推荐使用InstanceMethods模块.如果我理解正确,我们应该只在(实际上它只是在模块的主体中):included块中定义我们的方法
# edit: don't do this! The method definition should just be in the body of the module
included do
def my_method; end
end
Run Code Online (Sandbox Code Playgroud)
我只是想知道是否有人知道他们为什么决定那样做?
Sim*_*tsa 27
让我们看看你首先链接的例子.
module TagLib
extend ActiveSupport::Concern
module ClassMethods
def find_by_tags()
# ...
end
end
module InstanceMethods
def tags()
# ...
end
end
end
Run Code Online (Sandbox Code Playgroud)
将TagLib包含到类中时AS关注会自动使用ClassMethods模块扩展类,并包含InstanceMethods模块.
class Foo
include TagLib
# is roughly the same as
include TagLib::InstanceMethods
extend TagLib::ClassMethods
end
Run Code Online (Sandbox Code Playgroud)
但是您可能已经注意到我们已经包含了TagLib模块本身,因此其中定义的方法已经可以作为类中的实例方法使用.为什么你想要一个单独的InstanceMethods模块呢?
module TagLib
extend ActiveSupport::Concern
module ClassMethods
def find_by_tags()
# ...
end
end
def tags()
# ...
end
end
class Foo
include TagLib
# does only `extend TagLib::ClassMethods` for you
end
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7519 次 |
| 最近记录: |