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

Using helpers inside a controller (See related posts)

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 on this post

pianoman75 posts on May 26, 2006 at 04:18
Thanks so much for this - incredibly useful! Needed to use the strip_tags and strip_links functions to send plain text versions of an email. Normally when I try to do something that ends up being this complicated, there is a better, more "railsy" way of doing it that I've missed... can't work out how to do this without doing it within the controller though without adding lots of redundant extra steps.
adevadeh posts on Jun 22, 2006 at 10:07
yes! very clever and clean.
Thanks

You need to create an account or log in to post comments to this site.


Click here to browse all 4836 code snippets

Related Posts