ruby - extend module inside another module
I'm trying to define a couple of modules to easily add in some instance and class methods to other classes, here's what I'm doing:
module Foo module Bar def speak puts "hey there" end end module Baz extend Foo::Bar def welcome puts "welcome, this is an instance method" end end end class Talker include Foo::Baz end Talker.new.welcome Talker.speak
The output of this is:
welcome, this is an instance method undefined method 'speak' for Talker.class (NoMethodError)
I was expecting Talker to have the 'speak' method since it includes Foo::Baz which itself extends Foo::Bar.
What am I missing?
You can try this:
module Baz extend Foo::Bar def self.included(base) base.send :extend, Foo::Bar end def welcome puts "welcome, this is an instance method" end end
This will auto-extend all classes in wich Baz is included.
extend Foo::Bar in module Baz was in original snippet, this code do not influence on method def self.included(base).
class Talker extend Foo::Baz end
since you want to call Talker.speak as a class method and not as an instance method (like Talker.new.speak) you have to include the Foo:Baz in a way that the class will take the methods itself.
One possibility is to use 'extend' (as above) the other is modifying it's eigenclass:
class Talker class << self include Foo::Baz end end