0

[Rails] Calling view helpers from your controller

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.

1 comment

Anthony M.
 

You can also just add the module to your application controller.
Read more
Read less
  Cancel

Leave a comment