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
精彩评论