A popular mantra when learning Ruby is to be D.R.Y(Don’t Repeat Yourself), we do this in order to avoid looking like our friend Clint Eastwood up above. When building up a Rails application, you find yourself repeating code statements often; especially in your model controllers. Let’s take a look at a few CRUD actions in a controller for a post model within a blog application :
As you can see, we are already repeating ourselves in the actions ‘show’, ‘edit’, ‘update’, and ‘destroy’ in the very first line of each action . In each of these methods we are calling:
@post = Post.find(params[:id]
to acquire a post instance. To D.R.Y our code up in the controller, we can add a controller filter that is run prior to each action. Filters are methods that can be run before, after, or around controller actions. For the purpose of this instance, we want to use a “before” filter since we want this code to run before our actions.
Creating The Helper Method
Before implementing our before_action filter , we need to establish a helper method under ‘private’ that contains the code we are repeating:
We can name the helper method something simple such as ‘find_post’.
Now that we have our helper method established, we can implement our before_action filter on the first line of our controller. The syntax is shown below:
After calling our helper method, we specify which controller actions we want this to be called on:
only [:show, :edit, :update, :destroy]
This now lets our controller know that before carrying out these actions, we want to run ‘find_post’ in our show, edit, update, and destroy actions without explicitly writing it out. Awesome!
Hopefully now you can stay a little dryer out there in the programming world.
For more documentation on controller filters here!