views:

33

answers:

2

How could one do switch in ruby on rails something like:

case controller "home" 
  do home
case controller "about"
  do about
else 
  do home

I currently have this code:

<% case current_page(:controller) %>
      <% when "forums" %>
          <%= render :partial => 'shared/sidebar/sidebar_forums' %>
      <% when "events" %>
          <%= render :partial => 'shared/sidebar/sidebar_events' %>
      <% else %>
          <%= render :partial => 'shared/sidebar/sidebar_frontpage' %>
      <% end %>
A: 

Quoting from http://rails.nuvvo.com/lesson/6371-action-controller-parameters:

The params hash will always contain the :controller and :action keys, but you should use the methods controller_name and action_name instead to access these values. Any other parameters defined by the routing, such as :id will also be available.

So you should definitely be able to access it via params[:controller], and, if the controller_name method is in scope in a view, you should use that instead.

As for the switch syntax itself, you do need to do it like

case controller_name
when "home"
  do_home
when "about"
  do_about
else
  do_default
end

You could do some hacking and get

case true
when controller "home"
  do_home
when controller "about"
  do_about
else
  do_default
end

But why?

Martin DeMello
+1  A: 

Whenever you had to do something like this, that means there is something not right with the application design. Not that I have never done that in the past but I dont do this now and it is being frowned upon.

Instead of doing what you are doing now, if you namespace your controllers appropriately according to their responsibilities, after all they are just classes and handle the requests coming from the users,etc., then you may not have to do this switch statement. For example, after namespacing them you may have different layouts made of different partials for your views which may not require you to do this switching in your controller/views hence keeping the code clean.

nas