Reputation: 75
For example I have some class with this initialization:
class SomeClass < ActiveRecord
call_some_method('bla_bla_bla')
def some_method
return 1
end
# end of initialization or definition(not really sure, sorry)
# and here I want to call some code which can be added in other place of project
end
And I want to add the hook with my own code which can add or call methods of class after initialization. I don't have ability to add some code into class definition directly and here I don't mean about initialization of class instances.
Is there any way to do this?
Upvotes: 1
Views: 1558
Reputation: 62648
ActiveRecord has after_initialize and after_find hooks, which you can use to run code after a record is initialized (via new or build) or loaded (via find).
You can use something like:
class SomeClass
after_initialize :do_my_setup
def do_my_setup
# Your code here
end
end
Which would monkeypatch SomeClass to run your setup method after a new record is instantiated. You could use this to patch in new methods to instances of ActiveRecord objects, but this will have some implications for the Ruby method cache, and is generally considered a bad idea if you can avoid it.
If you just need to add new methods to the SomeClass
class - instance or class - you can just monkeypatch them in via the standard Ruby class extension mechanisms.
Upvotes: 1