在课程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
而不必在单例类中实现它?
答案 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