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.