views:

50

answers:

1

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?

+9  A: 

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
Mark Rushakoff