Front-End Developer & Consultant

Accessing view helpers in your controller

Posted by Mike Scriber on Friday, February 22, 2008

Today I had an interesting dilemma come about, which was using the text helper truncate and pluralize within a controller.

I’ve come across a solution from Lars Pind, which opens up the module and makes them module methods. Follow the steps below and you’ll be on your way to using text helper methods within your controllers in just a few minutes.

Step One
Create actionpack_ext.rb in your /lib directory. You can name this file anything you would like.

Step Two
Copy below code snippet into actionpack_ext.rb


                  module ActionView
                    module Helpers
                      module TextHelper
                        module_function :pluralize, :truncate
                      end
                    end
                  end
                  

Step Three
Open up environment.rb and add a require to actionpack_ext.rb.

Step Four
Restart your server

Once these steps are complete you can now call this new module method by ActionView::Helpers::TextHelper.truncate or ActionView::Helpers::TextHelper.pluralize within your controller.

Hope this helps and thanks Lars for posting your solution.

Comments

Great find Mike!

Nathan Rambarran on Tuesday, February 26, 2008

Add Comment


Search Site

Search Mike Scriber

About Mike

Mike Scriber is a front-end developer located in Toronto, Ontario. Mike takes pride in knowing his work is usable, accessible and standard compliant.

More about Mike

Mike Scriber's LinkedIn Profile

Tags

Archives

My Links