Beginning meta-programming question

I’m pretty new to ruby, and just playing around. I can’t work out why
following won’t work, though:

  1. module TrackInheritors
  2. def self.extended(parent)
  3.  class << parent
  4.    puts self
  5.    @@inheritors = []
  6.    def self.inheritors
  7.      @@inheritors
  8.    end
  9.    def self.inherited(child)
  10.      @@inheritors << child
  11.    end
  12.  end
  13. end
  14. end
  15. class Parent
  16. extend TrackInheritors
  17. end
  18. class Child1 < Parent
  19. end
  20. class Child2 < Parent
  21. end
  22. puts Parent.inheritors
  23. -:28: undefined method `inheritors’ for Parent:Class


I’m a noob myself so sorry if I give incorrect information but I think
you have a going out of scope issue. The inheirtors method is defined
within the class that starts on line 3. However, the class it’s put in
is inside the extended method on line 2, so what I think is going on is
that by the time you’re trying to the inheirtors method, its class has
already gone out of scope since it’s called after the extended method
has ended.

On Mon, Jul 26, 2010 at 6:48 AM, Andrew W. [email protected]

  1.      @@inheritors
  2. extend TrackInheritors
  3. -:28: undefined method `inheritors’ for Parent:Class


When you open the singleton class of parent, you don’t need to define
the methods for “self.”, just define them directly, cause you are
already on the singleton class:

module TrackInheritors
def self.extended(parent)
class << parent
puts self
@@inheritors = []

  def inheritors

  def inherited(child)
    @@inheritors << child


class Parent
extend TrackInheritors

class Child1 < Parent

class Child2 < Parent

puts Parent.inheritors

$ ruby inheritors.rb

I’m not really sure where were you defining those methods, in the
singleton class of the singleton class?


This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs