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?
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?
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
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