views:

670

answers:

2

I have a View that can vary significantly, depending on the 'mode' a particular user has chosen.

I thought I would extract the different behavior into two different Helpers, and then have code like this in the Controller:

class MyController < ApplicationController

case mode
when 'mode1'
  helper "mode1"
when 'mode2'
  helper "mode2"
else
  raise "Invalid mode"
end

etc...

Once the correct helper is loaded, then a statement like <%= edit_item %> , which is defined in both helpers, will load the correct form for the particular 'mode'.

This works beautifully in development, but in production, the case statement is only run once. Then you are stuck with whatever helper was first loaded (Duh! I should have known that.)

I have thought of other ways to achieve what I need to do, but I still think this use of Helpers is a nice clean way to change behavior of a View.

Does anyone know how I can load (or reload) a helper at runtime?

TIA: John

+1  A: 

After doing some more digging on this question, I'm starting to think this is a dumb idea... The implications of replacing modules at run time on a multi-user system don't look good.

Unless someone comes up with a bright idea that changes my mind, I'll retract this question by the end of the day.

-- John

John
+1  A: 

I can think of a few ways to do this, but not sure about loading modules as you were suggesting.

Load different partials and choose which to load based on the state.

<% if @mode = 'mode1 %>
  Mode 1:
  <%= render :partial => 'mode1' %>
<% else %>
  Mode 2:
  <%= render :partial => 'mode2' %>
<% end %>

Or if you wanted to keep that logic out of the view (which might be a good thing), you could put something in your controller to render different actions based on the mode:

def index
   @mode = params[:query]
   case @mode
     when 'mode1' then render :action => "mode1"
     when 'mode2' then render :action => "mode2"
     else raise "Invalid mode"
   end
end

Which seems much better than putting that logic in the view.

csexton