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?

Answers


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.

PS:

extend Foo::Bar in module Baz was in original snippet, this code do not influence on method def self.included(base).


try this:

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

Need Your Help

Filter by COUNT(*)?

mysql sql

Is it possible to group results and then filter by how many rows are in the group?

load jQuery-Templates from external file?

jquery templates jquery-templates

I just started using jQuery's template engine. Which looks quite nice so far. Yet i wonder if it's possible to load templates from an external file somehow. Imagine having loads of templates. This ...