Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

module extending other modules in Ruby

I have read quite a few answers here in this regards, but I still cant figure out why the following doesn't work

module A
  def a
    puts 'hi'
  end
end

module B
  extend A
end

class C
  extend B
  def b
    a
  end
end
C.new.b # undefined local variable or method `a' for #<C:...

I've also tried with:

module B
  def self.included(recipient)
    recipient.extend A
  end
end

Hoping C will get extended (but I guess the hierarchy is then wrong)

Important: The Problem is that I have a module that requires to be extended memoist, and I want to add some functionality to it.

How can I achieve that and why is the first example not working?

like image 545
estani Avatar asked Sep 18 '25 15:09

estani


1 Answers

extends adds the methods from the module passed as argument as 'class methods'. What you're looking for is include, which adds methods from (in this case) A module as instance methods, just like you want it to:

module A
  def a
    puts 'hi'
  end
end

module B
  include A
end

class C
  include B
  def b
    a
  end
end
C.new.b
# hi
like image 182
Marek Lipka Avatar answered Sep 21 '25 08:09

Marek Lipka