开发者

ruby - extend module inside another module

开发者 https://www.devze.com 2023-02-20 15:04 出处:网络
I\'m trying to define a c开发者_StackOverflow社区ouple of modules to easily add in some instance and class methods to other classes, here\'s what I\'m doing:

I'm trying to define a c开发者_StackOverflow社区ouple 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.

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
0

精彩评论

暂无评论...
验证码 换一张
取 消