2

Basically I'd like to extend the Time class to add this method:

def round_to_fifteen()
    return Time.at((self.to_i / 900).round * 900)
end

How do I achieve this and where should I put the file that extends the Class?

Sheldon
  • 9,639
  • 20
  • 59
  • 96

2 Answers2

3

Conventionally, this kind of thing goes in lib/. I'd just have something like lib/time_extensions.rb which is required from an initializer.

You would simply re-open the Time class and add the method desired, like so:

class Time
  def round_to_fifteen()
    return Time.at((self.to_i / 900).round * 900)
  end
end

Then, any Time object will have the #round_to_fifteen method available. You can see this in the console:

2.0.0p247 :004 > class Time
2.0.0p247 :005?>   def round_to_fifteen()
2.0.0p247 :006?>       return Time.at((self.to_i / 900).round * 900)
2.0.0p247 :007?>     end
2.0.0p247 :008?> end
 => nil
2.0.0p247 :009 > Time.now.round_to_fifteen
 => 2013-12-28 13:15:00 -0700
Chris Heald
  • 61,439
  • 10
  • 123
  • 137
  • I'm sorry to be a complete 'Noob' but how do I require it from an initializer? – Sheldon Dec 28 '13 at 20:32
  • 2
    Rails has the config/initializers directory. You can create a file in there (I like mine called something like `01_includes.rb` or whatnot), then `require File.join(Rails.root, 'lib/time_extensions')` in there. That'll require your extensions file when Rails boots up, re-open the Time class, and add your method. – Chris Heald Dec 28 '13 at 20:33
1

You could literally put this anywhere you want to use it, you could write

    class Time

      def round_to_fifteen
        return Time.at((self.to_i / 900).round * 900)
      end
    end

To use this, you would just write

timestamp_object.round_to_fifteen
Sheldon
  • 9,639
  • 20
  • 59
  • 96
OneChillDude
  • 7,856
  • 10
  • 40
  • 79