Beginning meta-programming question

Discussion in 'Ruby' started by Andrew Wagner, Jul 26, 2010.

  1. [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)
     
    Andrew Wagner, Jul 26, 2010
    #1
    1. Advertisements

  2. 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.
     
    Jesús Gabriel y Galán, Jul 26, 2010
    #2
    1. Advertisements

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 (here). After that, you can post your question and our members will help you out.