Reputation: 5127
In class Foo
I'd like to include method Bar
under certain conditions:
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
Is there any cleaner (and clearer) way to achieve the include
in the method without having to do it inside the singleton class?
Upvotes: 0
Views: 369
Reputation: 258528
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
Upvotes: 11