In this post, lets see how to extend
ActiveRecord::Base class to add custom methods.
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
ClassMethods has defined a method to list top ten results.
In the end the created module
ActiveRecordExtension is included in
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.
will list last 10 employees or users created.
Similarly we can add instance methods too.
The above applies only to
Rails 4.2 and below.
ApplicationRecord will be a single point of entry for all the customizations and extensions needed for an application, instead of monkey patching