How to Use ActionView Helpers in Your Rails Controller
Author: ceefour | Filed under: Rails
Sometimes when developing a Ruby on Rails web application, you want to use an ActionView helper method inside your controller. The following tip is from Gabriel Gironda 1.
This is incredibly straightforward and more of an occasional convenience, but I thought I’d throw it out there anyway.
One use case is 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
Don’t use the method name “helper” because Rails already uses that. Just “help” works fine.
No related posts.
Related posts brought to you by Yet Another Related Posts Plugin.
Pingback: pharm tech duties