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)

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

app/models/event.rb
class Event < ActiveRecord::Base
  include UtilityHelper
 
  def to_s
    UtilityHelper.camelcase_to_spaced("This an Event object")
  end
end

app/helpers/events_helper.rb
module EventsHelper
  include UtilityHelper
end

app/controllers/event_controller.rb
class EventController < ApplicationController
  include UtilityHelper
end


app/views/events/index.html.erb
<%=UtilityHelper.camelcase_to_spaced(event[:event_type])%&rt;

Advertisements

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

    Hello!

    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?

    Thanks!

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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: