-1

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

class Anything
  include Foo

  initializers :hello, :goodbye
end

module Foo

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

end

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

4

2 回答 2

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
于 2013-03-03T21:43:22.587 回答
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
于 2013-03-03T21:47:54.987 回答