Ruby:方法中包含的模块意味着什么?

时间:2011-01-17 10:15:51

标签: ruby module

我知道模块可以包含在类或其他模块中。 但是,我看到here模块包含在方法中。这意味着什么?

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

1 个答案:

答案 0 :(得分:4)

在这种情况下,定义的方法应在类级别调用,如下所示:

class Foo
    include ActsAsVotable
    acts_as_votable
end

Ruby有这个奇妙/可怕(取决于你问谁)功能,你可以动态定义一个类。在这里,acts_as_votable方法首先调用has_many(向类Foo添加一些方法),然后将cast_vote方法添加到Foo类中include 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