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

Snippets has posted 5883 posts at DZone. View Full User Profile

Using Helpers Inside A Controller

03.29.2006
| 103914 views |
  • submit to reddit
        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

I have used this method. Another useful tidbit--some of your own helper methods may expect the params hash 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 end

Snippets Manager replied on Thu, 2006/08/24 - 7:30pm

In any controller, there is a "@template"-instance and you can call helper methods (like pluralize) on this: class XyController < ApplicationController def do_it the_number = params[:the_number] the_word = params[:the_word] result = @template.pluralize(the_number, the_word) end I 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

yes! very clever and clean. Thanks

Snippets Manager replied on Fri, 2006/05/26 - 4:16am

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.