views:

421

answers:

2

#inherited is called right after the class Foo statement. I want something that'll run only after the end statement that closes the class declaration.

Here's some code to exemplify what I need:

class Class
  def inherited m
    puts "In #inherited for #{m}"
  end
end

class Foo
  puts "In Foo"
end
puts "I really wanted to have #inherited tiggered here."


### Output:
# In #inherited for Foo
# In Foo
# I really wanted to have #inherited tiggered here.

Does anything like that exist? Can it be created? Am I totally out of luck?

+3  A: 

You may be out of luck. But that's only a warning, not a definitive answer.

Ruby hooks the beginning of the class definition, rather than the end, for Class#inherited b/c ruby class definitions don't have a real end. They can be reopened any time.

There was some talk a couple years ago about adding a const_added trigger, but it hasn't gone through yet. From Matz:

I'm not going to implement every possible hook. So when somebody comes with more concrete usage, I will consider this again. It would be const_added, not class_added.

So this might handle your case - but I'm not sure (it may trigger on the start too, when it's eventually implemented).

What are you trying to do with this trigger? There may be another way to do it.

rampion
I'm trying to add behavior to activerecord models, but I need all the model customizations to go through before I mess with it. Right now I'm just including the extension module manually at a point in the model where everything I need has been set.
kch
kch
+1  A: 

If you are willing to assume your Ruby implements ObjectSpaces, you could could look up all model instances after the fact, and then modify them appropriately. Google suggests http://phrogz.net/ProgrammingRuby/ospace.html

Justin Love
I suspect that wouldn't go so well with Rails's class reloading.
kch