Never been to DZone Snippets before?

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

About this user

« Newer Snippets
Older Snippets »
Showing 1-1 of 1 total  RSS 

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.
« Newer Snippets
Older Snippets »
Showing 1-1 of 1 total  RSS