Learn to write Ruby on Rails Concerns to re-use code in your Models, for example with ActiveRecord callbacks.
When writing an extension for a Ruby on Rails model, an ActiveSupport Concern could be a good choice. They work like mixin modules that can be included in a class, but have some extra benefits for Rails models, such as the ability to add Callbacks.
This post will show you how to DRY out your code so that your Concern not only adds custom methods to records, but also add Callbacks to trigger on create, update, and delete. It will also cover how to run your tests in a way that manages these Callbacks.
You can add your own code to be run when these Callbacks are triggered. One way to do this is by using an ActiveSupport::Concern, which can then be easily shared across multiple models.
More on Callbacks can be read about in Rails Guides: Active Record Callbacks.
You can define a Concern using a module that is extended by an ActiveSupport::Concern. Then add the methods and other code you wish to include.
To add your Concern to a model, you include as you would a module. Then you can tell your model's callbacks to run the methods from the Concern when they are triggered.
This means you can create records and call the Concern's email method on it.
You can also define in your Concern which methods to call for specific callbacks when it is included in a model. This is achieved by using the included method within your Concern.
Now your models are kept skinny and all the logic and callback definitions are kept in the Concern.
It is important to bear in mind testing when creating Callbacks, because they will be run during your test suite unless you take certain steps to manage them.
For example, you might have a ActiveRecord callback such as after_save :email that uses the Rails ActionMailer to send an email confirmation once a user has been saved.
This would post an email every time a record is saved in your tests.
In order to stop this, you need to stub this method call. Depending on your codebase, you either stub individual files or the entire test suite.
Warning: this may slow down your test suite!
But then when you do want to test the callback, you need to create the record, set the expectation on it, then call a method that will trigger the callback.
Concerns are a great way to extract logic out of Ruby on Rails models and controllers in a reusable way.
If you are interested in trying out other ways of managing your Ruby on Rails code, then a popular approach is to use Service Objects, which perform a specific task in your app.
An explanation of assigns and how to use it to test instance variables in Ruby on Rails views and controllers.
Recommended websites, tutorials, blogs and other media for learning Ruby on Rails.
A guide to becoming a Ruby on Rails contributor.