Created
August 12, 2009 17:41
-
-
Save cflipse/166632 to your computer and use it in GitHub Desktop.
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
def interpret_time(time) | |
return nil if time.blank? | |
return time if time.kind_of?(Time) or time.kind_of?(Date) | |
named_time(time) || time_by_regex(time) || Time.parse(time) | |
end | |
def named_time(time) | |
case time.downcase | |
when "today" : Date.today | |
when "now" : Time.now | |
when "tomorrow" : Date.tomorrow | |
when "yesterday" : Date.yesterday | |
else nil | |
end | |
end | |
def time_by_regex(time) | |
directional_regex = /(ago|from now)$/ | |
time_regex = /(\d+) (minute|hour|day|week|month|year)s?/i | |
direction= time.scan(directional_regex).flatten | |
shifts = time.scan(time_regex) | |
return nil if direction.empty? or shifts.empty? | |
result = Time.now | |
backward = (direction.first == "ago") | |
shifts.each do |count, unit| | |
adjustment = count.to_i.send(unit) | |
result = backward ? (result - adjustment) : (result + adjustment) | |
end | |
result | |
end |
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
Given a document posted today | |
Given a document posted 2 months, 5 days ago | |
Given my last login was 3 hours ago | |
Given a task due 1 week from now |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment