Skip to content

Instantly share code, notes, and snippets.

@Rojo
Created May 21, 2014 14:17
Show Gist options
  • Save Rojo/78cf36cc6955984efd39 to your computer and use it in GitHub Desktop.
Save Rojo/78cf36cc6955984efd39 to your computer and use it in GitHub Desktop.
Using method_missing to extend Fixnum to handle some time conventions in a more natural way.
# This combines the examples given here http://pastebin.com/zxsur5MX
# and here http://pastebin.com/agjb5qBF
# Note: Time.now returns current time as seconds since epoch
module TimeConventions
TIME_CONVENTIONS = {
'second' => 1,
'minute' => 60,
'hour' => 60 * 60,
}
def method_missing(method_id, *args, &block)
singular_convention = method_id.to_s.gsub(/s$/, '')
if TIME_CONVENTIONS.has_key? singular_convention
self * TIME_CONVENTIONS[singular_convention]
else
super
end
end
def ago ; Time.now - self ; end
def from_now ; Time.now + self ; end
end
class Fixnum
include TimeConventions
end
puts Time.now
# => Mon Nov 07 10:18:10 -0800 2011
puts 1.minute.ago
# => Mon Nov 07 10:17:10 -0800 2011
puts 5.minutes - 4.minutes
# => 60
puts 1.hour.from_now
# => Mon Nov 07 11:18:15 -0800 2011
puts 3.hours.from_now
# => Mon Nov 07 13:18:15 -0800 2011
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment