Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to have an inherited callback in ruby that is triggered after the child class is defined instead of before [duplicate]

Possible Duplicate:
ruby: can I have something like Class#inherited that's triggered only after the class definition?

class A
  def self.inherited(child)
    puts "XXX"
  end
end

class B < A
  puts "YYY"
end

prints out

XXX
YYY

I'd prefer

YYY
XXX

if I could get it somehow.

like image 619
bradgonesurfing Avatar asked Aug 17 '11 13:08

bradgonesurfing


People also ask

How do you inherit parent classes in Ruby?

Whenever you want to call parent class method of the same name so you can simply write super or super(). Example: Ruby.

Can a Ruby module be inherited?

The Ruby class Class inherits from Module and adds things like instantiation, properties, etc – all things you would normally think a class would have. Because Module is literally an ancestor of Class , this means Modules can be treated like classes in some ways. As mentioned, you can find Module in the array Class.

What is single inheritance in Ruby?

In Ruby, a class can inherit from one other class. This is called single inheritance. Some languages have support for multiple inheritance, which means a class can inherit from multiple classes.


1 Answers

You can trace until you find the end of the class definition. I did it in a method which I called after_inherited:

class Class
  def after_inherited child = nil, &blk
    line_class = nil
    set_trace_func(lambda do |event, file, line, id, binding, classname|
      unless line_class
        # save the line of the inherited class entry
        line_class = line if event == 'class'
      else
        # check the end of inherited class
        if line == line_class && event == 'end'
          # if so, turn off the trace and call the block
          set_trace_func nil
          blk.call child
        end
      end
    end)
  end
end

# testing...

class A
  def self.inherited(child)
    after_inherited do
      puts "XXX"
    end
  end
end

class B < A
  puts "YYY"
  # .... code here can include class << self, etc.
end

Output:

YYY
XXX
like image 183
Sony Santos Avatar answered Sep 21 '22 16:09

Sony Santos