Extend ActiveRecord::Base
In this post, lets see how to extend ActiveRecord::Base class to add custom methods.
module ActiveRecordExtension
extend ActiveSupport::Concern
# add your static(class) methods here
module ClassMethods
#E.g: Order.top_ten
def top_ten
limit(10)
end
end
end
# include the extension
ActiveRecord::Base.send(:include, ActiveRecordExtension)In the above example module ActiveRecordExtension has defined a module ClassMethods which is the standard way of creating class methods to be included in other classes or modules using ActiveSupport::Concern.
This ClassMethods has defined a method to list top ten results.
In the end the created module ActiveRecordExtension is included in ActiveRecord::Base dynamically.
Create a rails initializer active_record_extension.rb and add the above code in that file.
The extension is added to the ActiveRecord::Base on boot of the rails and ready to be used on all active record models.
Now we can use this method top_ten on all the models.
Employee.top_ten
User.top_tenwill list last 10 employees or users created.
Similarly we can add instance methods too.
Note:
The above applies only to Rails 4.2 and below.
With Rails 5, ApplicationRecord will be a single point of entry for all the customizations and extensions needed for an application, instead of monkey patching ActiveRecord::Base