Is there a hook similar to Class#inherited that's triggered only after a Ruby class definition?

前端 未结 8 2125
无人共我
无人共我 2020-12-03 13:35

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

8条回答
  •  抹茶落季
    2020-12-03 14:09

    I had the same question when trying to automatically add generic validations to all models. The problem was that if the model used #set_table_name then my code that added added the validations based on the DB data-types would blow up because it was guessing at the table name based on the name of the model (because #inherited was getting called BEFORE #set_table_name).

    So just like you, I was really looking for a way to get #inherited to fire AFTER everything in the model had already been loaded. But I didn't really need to take it that far, all I needed was something that fired AFTER #set_table_name. So it turned out to be a simple as aliasing the method. You can see an example of what I did here: https://gist.github.com/1019294

    In a comment above you stated "I'm trying to add behavior to activerecord models, but I need all the model customizations to go through before I mess with it". So my question to you is if there are specific model customizations you care about, if so then maybe you could use an aliasing approach to achieve your desired result.

提交回复
热议问题