Ruby On Rails Filters

Learn how to create dynamic filters in Ruby on Rails w/ an example of filtering users by name & email.

What are Ruby on Rails Filters?

Ruby on Rails Filters are methods that are run before, after or around actions in the controller. They are used to filter or modify parameters, log information about requests or responses, redirect to other pages and more. Filters can also be used to restrict access to certain controller actions.

Filters are defined in the controller with the before_action, after_action, and around_action methods. Before and after filters are run before and after each controller action, respectively. Around filters are run around each controller action and have access to the controller action's return value.

Examples of Ruby on Rails Filters

Below are some examples of how Ruby on Rails Filters are used:

A before filter example to set a session variable before an action is run:

before_action :set_session_variable

def set_session_variable
  session[:session_variable] = "value"
end

An after filter example to log information about a request:

after_action :log_request

def log_request
  logger.info "Request: #{request.method} #{request.url}"
end

An around filter example to measure request time:

around_action :measure_request_time

def measure_request_time
  start_time = Time.now
  yield
  end_time = Time.now
  logger.info "Request time: #{end_time - start_time}"
end

A before filter example to restrict access to certain controller actions:

before_action :restrict_access

def restrict_access
  if current_user.is_admin?
    true
  else
    flash[:error] = "You are not authorized to do this action."
    redirect_to root_path
    false
  end
end

These are just some examples of how Ruby on Rails Filters can be used. Filters can be used for a variety of purposes and are an important part of Rails development.

Answers (0)