DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world
Using Helpers Inside A Controller
Ripped from
http://gabriel.gironda.org/articles/2006/02/08/using-helpers-inside-a-controller
This is incredibly straightforward and more of an occasional convenience, but I thought I'd throw it out there anyway. You may find that sometimes, even though the controller obviously isn't the view, that you want to use some of the helper methods available.
The only case I've come across so far is wanting to use pluralize() in a flash message and not have to do it by hand using the inflector. You could include ActionView::Helpers::TextHelper in the controller, but that fills your namespace with crap.
Put this in the class ApplicationController instead:
def help
Helper.instance
end
class Helper
include Singleton
include ActionView::Helpers::TextHelper
end
Then you can just use it like so:
def check_for_max_donkeys
if Donkey.find_fit_donkeys.size == APP_SETTINGS['max_fit_donkeys']
flash_error "The maximum of #{help.pluralize(APP_SETTINGS['max_fit_donkeys'], 'donkey')} has been reached."
redirect_to_index
end
end
Update: Don't use the method name "helper" because Rails already uses that. Just "help" works fine.






Comments
Ed Ruder replied on Tue, 2006/11/21 - 12:36am
paramshash to be set up. It's easy to do so:def helpers Helper.instance.params = self.params Helper.instance end class Helper include Singleton include ActionView::Helpers::TextHelper include MyHelper # some methods depend on params being set up endSnippets Manager replied on Thu, 2006/08/24 - 7:30pm
class XyController < ApplicationController def do_it the_number = params[:the_number] the_word = params[:the_word] result = @template.pluralize(the_number, the_word) endI found this trick in http://media.railscasts.com/videos/132_helpers_outside_views.mov. Ryan is not sure if this use is intended but it is very short and today it works.Adeh DeSandies replied on Thu, 2006/06/22 - 10:04am
Snippets Manager replied on Fri, 2006/05/26 - 4:16am