Dynamically add method to ActiveRecord class

If you have a Rails application that needs to include models from another Rails application, oftentimes you will want to add features to those methods, but you cannot since you cannot touch the other Rails app’s codebase.

If this is the case, you can use class_eval, which Neeraj explains nicely.

For example, if you want to add an after_save to a class Example :

Example.class_eval do
after_save :somemethod

def somemethod
end
end

Note that you dont wanna put that code under vendor/plugins/ . Instead, put it under a place where it’s executed everytime.

Leave a Comment

Please note: Comment moderation is enabled and may delay your comment. There is no need to resubmit your comment.