views:

175

answers:

2

I plan to create a method that would format a Time in a specific way (specialized formatting in Russian).

I would like to reuse this helper method in multiple models, controllers and possibly views. Also I would like to call this helper method on instance of Time class like follows:

t=Time.now
t.my_super_shiny_helper

Question: where should I implement this helper? (module or class, where in application directory structure?). After creating it, how should I call it?

I'm new to ruby/rails and struggle to get this working in a proper way.

Thank you.

+8  A: 

I would add a file to lib/time_extensions.rb

class Time
  def my_shiny_helper
    ...
  end
end

And in an initializer file in config/intitializers

require 'time_extensions'

If the extensions grow a bit and are something you want to reuse think of putting it into a plugin for easy inclusion. Or even a gem.

Squeegy
+4  A: 

If you just want to format a time, a clean approach in Rails (as given in Agile Web Development) is to extend the formats used in the to_s method:

ActiveSupport::CoreExtensions::Time::Conversions::DATE_FORMATS.merge!( 
  :russian => "%A %d %B %Y" 
) 

Time.now.to_s(:russian) #=> "Tuesday 17 February 2009"

Include the first bit in either config/environment.rb or in a file in config/initializers.

Ian Terrell