我知道模块可以包含在类或其他模块中.但是,我在这里看到模块包含在方法中.这意味着什么?
module ActsAsVotable
module ClassMethods
def acts_as_votable
has_many :votes, :as => :votable, :dependent => :delete_all
include InstanceMethods # What does this means ??
end
end
module InstanceMethods
def cast_vote( vote )
Vote.create( :votable => self, :up => vote == :up )
end
end
end
Run Code Online (Sandbox Code Playgroud)
在这种情况下,定义的方法应该在类级别调用,如下所示:
class Foo
include ActsAsVotable
acts_as_votable
end
Run Code Online (Sandbox Code Playgroud)
Ruby 有这个奇妙/可怕(取决于你问的人)的特性,你可以动态定义一个类。这里,acts_as_votable方法首先调用has_many(这会向类添加一些方法)Foo,然后通过.cast_voteFooinclude InstanceMethods
所以,你最终会得到相当于:
class Foo
# Will add further methods.
has_many :votes, :as => :votable, :dependent => :delete_all
# include InstanceMethods
def cast_vote( vote )
Vote.create( :votable => self, :up => vote == :up )
end
end
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
562 次 |
| 最近记录: |