开发者

Ruby Module Inclusion in Methods

In class Foo I'd like to include method Bar under certain conditions:

 modul开发者_如何学JAVAe 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

Is there any cleaner (and clearer) way to achieve the include in the method without having to do it inside the singleton class?


extend is the equivalent of include in a singleton class:

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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜