如何编写ruby模块以允许类定义中的方法

时间:2013-03-03 21:14:48

标签: ruby

很难搞清楚这一点。假设我想编写一个模块,当包含它时,它将允许类通过调用带符号的方法来定义方法

class Anything
  include Foo

  initializers :hello, :goodbye
end

module Foo

  # What goes in here? Its not 
  # def self.initializers(*symbols)

end

attr_accessible语法相同。试图在Rails源代码中找到它,但是,好吧..

2 个答案:

答案 0 :(得分:2)

module Foo

  def self.included(base)
    base.extend ClassMethods
  end

  module ClassMethods
    def initializers *names
      names.each do |name|
        define_method name do
          'ok'
        end
      end
    end
  end

  def self.included(base)
    base.extend ClassMethods
  end
end

class Anything
  include Foo

  initializers :hello, :goodbye
end

puts Anything.new.hello #=> ok

答案 1 :(得分:1)

例如:

module Foo

  def self.included(base) 
    block = Proc.new  do |*symbols|
      puts symbols.inspect
    end
    base.class.send(:define_method, :initializers, block)  
  end

end

class Anything
  include Foo

  initializers :one, :two , :three

end