Staying D.R.Y With Before_Action

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:

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’.

Before_Action Syntax

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:

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!

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store