开发者

Ruby Module Inclusion in Methods

开发者 https://www.devze.com 2023-01-02 10:44 出处:网络
In class Foo I\'d like to include method Bar under certain conditions: modul开发者_如何学JAVAe Bar

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

精彩评论

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

关注公众号