How to execute code before action is called

Rails is a great framework! When you start building web apps with it, you will definitely fall in love with it!

Today I want to share with you one really cool feature - you have hooks (called Filters in Rails) that allow you to execute code before, after or around a controller action.

One of the cases I had was to validate the validity of the Authorization token in the headers before the requested action being executed. There're two cases: either the token is valid nor invalid. If it's the first case - the request is passed to the action, if it's the second - an error JSON and respective status code are returned as response.

So, lets see how I accomplished this task!

First, you have to create a method which will execute the validation logic. I called it validate_auth_token:

def validate_auth_token
  if request.headers["Authorization"].blank?
    render json: {'status_code': 403, message: 'Missing or wrong authentication token'}, status: 403 and return

Then you have to tell the controller that you want to execute this method before each action. This is pretty easy! Just add at the controller's top:

class ApiController < ActionController::API
  before_action : validate_auth_token

That's it! Really easy, right? 👻

For more information - review the official Ruby on Rails Documentation.