views:

45

answers:

1

Say, I have this in one of the controllers:

  def show
    case current_user.role
      when 'manager'
       render :text => 'Manager view!'
      when 'admin'
       render :text => 'Admin view!'
    end
  end

The thing is, that instead of 'render', of course, there's a bunch of code and it all stops look pretty very fast. Also, I have some other actions in my controller, which have to perform differently for each of the user roles. What's the best way to refactor it without having to write some sorts of 'ifs' and 'cases' in the action's body? I'd like to have 2 files - one for each of the user roles; or at least two different actions.

+1  A: 

if the 2 variations are significantly different and must be invoked from the same controller, you could use an around_filter and dispatch the controller.action_name to one of 2 classes that inherit from the same base.

if the 2 variations aren't so different that they require forking, ifs should be fine...

for the dispatching, it could be just a generic class that inherits from a base class. you can have a switch in your filter that creates the right object based on the role, then finally send(“#{action}”) on the object. i would only do that if the variations are so different that they merit 2 derived classes.

now aside from generic classes, you could also use the handy Components w/the render_component method. in most cases the overhead of dispatching to a component controller would be rather negligible. (this is kind of like a server-side transfer (Server.Transfer) in .net.)

jspcal
Could you specify the dispatching and inheritance part? What would it look like in this case? I'm not sure.
snitko