[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 include
d in a class. But there’s another way, which is to open up the module and make them also be module methods, like so:
Require this in yourmodule ActionView module Helpers module TextHelper module_function :pluralize, :truncate end end end
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
.
About Calvin Correli
I've spent the last 17 years learning, growing, healing, and discovering who I truly am, so that I'm now living every day aligned with my life's purpose.
1 comment
Leave a comment