Skip to content

Instantly share code, notes, and snippets.

@ptitfred
Last active December 14, 2015 12:59
Show Gist options
  • Save ptitfred/5090629 to your computer and use it in GitHub Desktop.
Save ptitfred/5090629 to your computer and use it in GitHub Desktop.
Relative time builder in Ruby - requires ActiveSupport Time extensions
require "active_support/time"
# in 3 days
Time.fluent("+3d")
# Tomorrow at 10 am
Time.fluent("+1d @10h")
class Time
def self.fluent(at)
at.split(' ').reduce(Time.now) do |time, part|
if part =~ /^(?<command>[\+@])(?<arguments>.*)$/
case $~[:command]
when '+'
time.advance( to_time_params($~[:arguments], true))
when '@'
time.change( to_time_params($~[:arguments]))
end
else
time
end
end
end
private
def self.to_time_params(arguments, plural=false)
if arguments =~ /(?<duration>[0-9]*)(?<unit>[dhm])$/
duration = $~[:duration].to_i
unit = case $~[:unit]
when 'd'
plural ? :days : :day
when 'h'
plural ? :hours : :hour
end
{ unit => duration }
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment