Beginning meta-programming question

A

Andrew Wagner

[Note: parts of this message were removed to make it a legal post.]

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

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

Jesús Gabriel y Galán

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

=A0 1. =A0module TrackInheritors
=A0 2. =A0 =A0def self.extended(parent)
=A0 3. =A0 =A0 =A0class << parent
=A0 4. =A0 =A0 =A0 =A0puts self
=A0 5. =A0 =A0 =A0 =A0@@inheritors =3D []
=A0 6.
=A0 7. =A0 =A0 =A0 =A0def self.inheritors
=A0 8. =A0 =A0 =A0 =A0 =A0@@inheritors
=A0 9. =A0 =A0 =A0 =A0end
=A0 10.
=A0 11. =A0 =A0 =A0 =A0def self.inherited(child)
=A0 12. =A0 =A0 =A0 =A0 =A0@@inheritors << child
=A0 13. =A0 =A0 =A0 =A0end
=A0 14. =A0 =A0 =A0end
=A0 15. =A0 =A0end
=A0 16. =A0end
=A0 17.
=A0 18. =A0class Parent
=A0 19. =A0 =A0extend TrackInheritors
=A0 20. =A0end
=A0 21.
=A0 22. =A0class Child1 < Parent
=A0 23. =A0end
=A0 24.
=A0 25. =A0class Child2 < Parent
=A0 26. =A0end
=A0 27.
=A0 28. =A0puts Parent.inheritors
=A0 29.
=A0 30. =A0# -:28: undefined method `inheritors' for Parent:Class
=A0 (NoMethodError)

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 =3D []

def inheritors
@@inheritors
end

def inherited(child)
@@inheritors << child
end
end
end
end

class Parent
extend TrackInheritors
end

class Child1 < Parent
end

class Child2 < Parent
end

puts Parent.inheritors


$ ruby inheritors.rb
#<Class:parent>
Child1
Child2

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

Jesus.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,764
Messages
2,569,566
Members
45,041
Latest member
RomeoFarnh

Latest Threads

Top