So far, it\’s RoR

Ruby on Rails, PostgreSQL, SVN, etc….

Using helpers in models, views, and controllers

Posted by Chirag Patel on July 8, 2008

Using this as a guide JLHPBv2: Using Helpers in Models in Rails, you can make a single Module that can be accessed from models, views, and controllers. The helpers automatically created in app/helpers/*_helpers.rb   might also be available anywhere as long as you include them.

I decided to make the methods in the helper class-scoped (using self below) so that the origin of the helper method is explicitly obvious in the call (eg. to_s below)

module UtilityHelper
  def self.camelcase_to_spaced(word)
    word.gsub(/([A-Z])/, " \\1").strip

class Event < ActiveRecord::Base
  include UtilityHelper
  def to_s
    UtilityHelper.camelcase_to_spaced("This an Event object")

module EventsHelper
  include UtilityHelper

class EventController < ApplicationController
  include UtilityHelper



2 Responses to “Using helpers in models, views, and controllers”

  1. Nice tip, Chirag. Kinda off topic, but I saw your comment on Matt McCray’s Sorta Nested Layouts post and was wondering if you still use that technique (instead of something like the nested layouts plugin). Thanks.

    P.S. I still owe you a cup of soup someday 😉

  2. Tom said


    Thanks for your guide. I am following your instructions to include a UtilityHelper in my model called Results, but I get this error:

    NameError in ResultsController#index
    uninitialized constant Result::UtilityHelper

    Any clues?


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: