方法中的Ruby模块包含

时间:2010-06-01 22:58:14

标签: ruby metaprogramming mixins

在课程Foo中,我想在某些条件下添加方法Bar

 module Bar
   def some_method
     "orly"
   end
 end

 class Foo
   def initialize(some_condition)
     if !some_condition
       "bar"
     else
       class << self; include Bar; end
     end
   end
 end

是否有更清晰(更清晰)的方法来实现方法中的include而不必在单例类中实现它?

1 个答案:

答案 0 :(得分:11)

extend相当于单个类中的include

module Bar
  def some_method
    puts "orly"
  end
end

class Foo
  def initialize(some_condition)
    extend(Bar) if some_condition
  end
end

Foo.new(true).some_method # => "orly"
Foo.new(false).some_method # raises NoMethodError