Lars Pind

internet software, coaching, and entrepreneurship

Lars Pind - internet software, coaching, and entrepreneurship
Check out Coach TV, my video blog on happiness and personal development for geeks.

[Rails] Calling view helpers from your controller

October 18, 2005 · See comments

When developing with Rails, I often find myself wanting to use the truncate or pluralize text helpers from a controller when I’m setting the flash notice to something like “Post #{truncate(@post.title)} was successfully saved” or “Updated #{pluralize(@posts.size, “post”)}”.

The methods are instance methods, not module methods, which means they can only be called after they’ve been included in a class. But there’s another way, which is to open up the module and make them also be module methods, like so:

module ActionView
  module Helpers
    module TextHelper
      module_function :pluralize, :truncate
    end
  end
end
Require this in your environment.rb, restart your server, and now you can call them with ActionView::Helpers::TextHelper.truncate and ActionView::Helpers::TextHelper.pluralize.

Btw, I like to have a file lib/actionpack_ext.rb for this and all my other mods to vanilla Rails ActionPack, and just require that file from my environment.rb.

blog comments powered by Disqus

Comments ↓

  • 1 Anthony M. // Jan 10, 2006 at 07:52 AM

    You can also just add the module to your application controller.