In a previous post, I mentioned Gabriel Gironda’s snippet showing how to use view helpers in a controller. Calling view-specific helpers from the controller is a particularly useful technique in AJAX callback methods where you need to replace some HTML. The alternative is rendering a partial, which I felt was cumbersome and overkill if you just need to replace a single string of text.
However, the above technique doesn’t work out of the box if you need to use a custom helper that you have written in your app/helpers directory tree. The trick is to use the extend method to mix-in your custom helper modules.
Here is an example, where I extend the help singleton object with the CompanyHelper module, in order to be able to the text_for_action and text_for_notice methods.
def ajax_add_to_portfolio
help.extend ::CompanyHelper
raise "Company doesn't exist!" unless @company
kind = params[:category]
raise help.text_for_action( kind )+" already performed!" if @company.in_portfolio?( @current_user, kind )
@current_user.portfolio_items.create!( :company_id => params[:id], :category => kind )
action_text = help.text_for_action( kind, :past_tense => true )
notice_text = help.text_for_notice( kind )
render :update do |page|
page.flash_then_fade :success, action_text
page.replace_html kind, notice_text
end
rescue Exception => e
handle_exception e
end
