Saturday 29 June 2013

Rails: changing templates by action

One of the main principles that I like follow when I am developing a Web application is: in your web app, the front end never must looks like your back end. That is, the admin zone and the public area must have their own CSS classes and layouts. The regular user, the admin and even the anonymous visitant to the site must feel clear the difference between one and another areas.

Typically we use Devise gem to set the actions that we wanna keep restricted and in most of the cases that areas share the same action names: new, edit, create, destroy, update, show. So in many cases those are the actions that we wanna present with the "admin" layout.

So in our app/controllers/application_controller.rb file we add the method:

# @@ - Class variable with actions 
@@actions = %w(new edit create destroy update index start show)

 # Layout for action method
 def layout_by_action
     action = params[:action]
     #raise action_name
     if @@actions.include?(action)
         self.class.layout "admin"
     else
         self.class.layout "application"
     end
end

And in the controller where we want to show different layouts we add:

 # load proper layout
  before_filter :layout_by_action

et voilà!, we have our admin restricted area. Of course you must have an admin layout like this in the views layout directory.

No comments: