Can I load the Rails helper at runtime?

I have a view that can vary significantly depending on the "mode" that a particular user has selected.

I thought that I would extract the different behavior into two different helpers, and then the controller should have this code:

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 an operator of the type <% = edit_item%>, which is defined in both helpers, will load the correct form for the particular "mode".

This works great in development, but in production, the case statement only runs once. Then you are stuck with any auxiliary was first loaded (Spirit, I should have known this.)

I thought of other ways to achieve what I need to do, but I still think that using helpers is a good clean way to change the behavior of a view.

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

TIA: John

+4
source share
2 answers

I can come up with several ways to do this, but I'm not sure about loading the modules as you suggested.

Download different partial files and choose which load to load based on state.

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

Or, if you want to save this logic from the view (which may be useful), you can put something in your controller to display various 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 

This seems a lot better than using this logic in a view.

+1
source

After you do even more operations on this issue, I begin to think that this is a stupid idea ... The consequences of replacing modules during the execution of a multi-user system do not look very good.

If someone does not come up with a bright idea that changes my mind, I will return this question by the end of the day.

- John

+1
source

All Articles