Setting Filters on Ruby on Rails Actions

Rails Framework relies on filters in order to pre-empt execution of Actions in Rails framework. Let’s look at one such filter being created in order to prevent unauthorized access to password protected pages. Accessing user related account pages is one such example when password protection is mandatory in order to prevent others from viewing person information.

We rely on ApplicationController class in order to set up our filters in Rail Framework. Here is just one example how this can be accomplished.

class ApplicationController < ActionController::Base
 before_filter :set_user

protected
 def set_user
  @user_name = User.find(session[“id])
 end
 def login_needed
  return true if @user_name
   no_access
  return false
 end
 def no_access
  flash[:access_message] = “No Access Requested”
  redirect to :controller =>’user_account’, :action=>login_screen
 end
end

There are two filters in the example above set_user and no_access. You can see that set_user is set up to run for each action due to before_filter in ApplicationController class. We set it in our superclass before all our controllers get execute. As a result, user_account object which we set up in this ApplicationController is available throughout our application.

Final step in our explanation of Rail filter is the actual protection of the actions in other controllers. Here is an example that will protect My Account from being accessed by unauthorized user.

class UserController < ApplicationController
 before_filter: login_required, :only=>:my_account
end

We also used concept of flash[] in the example above, which is a simply hash object used to pass data between pages/actions within a session. It is recommended approach to share data like error message from page to page.

Featured pages

Ruby

Set of Ruby Object Oriented Programming Language tutorials that cover such topics as Ruby strings, …

Rails

Rails Framework tutorial teaches you how to utilize de facto framework of choice for Ruby developme…

Ruby Duck Typing

“If an object quacks like a duck just go ahead and treat it as a duck” – this fun…

Regular Expressions

Ruby uses the =~ operator to check any given string against regular expression. For example, a stri…

Credit Card Number

Every last digit of any credit card is a check sum digit that is determined by all digits in front …

Ruby Arrays

Ruby Programming Language has built in support for Arrays. Arrays help you define some of the compl…

Ruby Hashes

Hashes are very similar to arrays in Ruby and hashes interface is similar to Ruby array interface. …

Ruby Code Block

Ruby is very unique language when it comes to code blocks. You can simply pass a code block to a me…