Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extend module inside another module

Tags:

ruby

I want to invoke method a from method of module B. How can I do it? I don't want to specify A::a every time.

module A
  def self.a
    "a"
  end
end

module B
  extend A

  def self.b
    a
  end
end

p B::b  # => undefined local variable or method `a' for B:Module
like image 652
Andrei Botalov Avatar asked Jan 04 '13 14:01

Andrei Botalov


2 Answers

When using extend or include, Ruby will only mixin the instance methods. Extend will mix them in as class methods, but it won't mix in the class methods. Therefore, an easy solution to your query:

module A
  def a  ## Change to instance
    "a"
  end
end

module B
  extend A

  def self.b
    a
  end
end

p B::b #=> "a"
p B.b  #=> "a"
like image 53
quandrum Avatar answered Oct 09 '22 00:10

quandrum


I found here a method to solve it but it doesn't look good to me:

module A 
  module ClassMethods
    def a
      puts "a"
    end
  end
  extend ClassMethods
  def self.included( other )
    other.extend( ClassMethods )
  end
end

module B
  include A

  def self.b
    a
  end
end

p B::b  # => "a"
like image 33
Andrei Botalov Avatar answered Oct 09 '22 02:10

Andrei Botalov