Last active
December 14, 2015 12:59
-
-
Save ptitfred/5090629 to your computer and use it in GitHub Desktop.
Relative time builder in Ruby - requires ActiveSupport Time extensions
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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