Using helper in mode;s, views, and controllers

So far, it\'s RoR

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;

View original post

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