lib/timeliness/parser.rb in timeliness-0.1.1 vs lib/timeliness/parser.rb in timeliness-0.2.0
- old
+ new
@@ -1,7 +1,8 @@
module Timeliness
module Parser
+ class MissingTimezoneSupport < StandardError; end
class << self
def parse(value, *args)
return value unless value.is_a?(String)
@@ -10,22 +11,15 @@
type = args.first
time_array = _parse(value, type, options)
return nil if time_array.nil?
- case type
- when :date
- time_array[3..7] = nil
- when :time
- time_array[0..2] = current_date(options)
- when nil
- dummy_date = current_date(options)
- time_array[0] ||= dummy_date[0]
- time_array[1] ||= dummy_date[1]
- time_array[2] ||= dummy_date[2]
- end
+ override_values_by_type(time_array, type, options) unless type == :datetime
make_time(time_array[0..6], options[:zone])
+ rescue NoMethodError => ex
+ raise ex unless ex.message =~ /zone/
+ raise MissingTimezoneSupport, "ActiveSupport must be loaded to use timezones other than :utc and :local."
end
def make_time(time_array, zone=nil)
return nil unless fast_date_valid_with_fallback(*time_array[0..2])
@@ -55,24 +49,43 @@
nil
end
private
+ def override_values_by_type(values, type, options)
+ case type
+ when :date
+ values[3..7] = nil
+ when :time
+ values[0..2] = current_date(options)
+ when nil
+ dummy_date = current_date(options)
+ values[0] ||= dummy_date[0]
+ values[1] ||= dummy_date[1]
+ values[2] ||= dummy_date[2]
+ end
+ end
+
def current_date(options)
now = if options[:now]
options[:now]
elsif options[:zone]
- case options[:zone]
- when :utc, :local
- Time.now.send("get#{options[:zone]}")
- when :current
- Time.current
- else
- Time.use_zone(options[:zone]) { Time.current }
- end
+ current_time_in_zone(options[:zone])
+ else
+ Timeliness.date_for_time_type
end
- now ||= Timeliness.date_for_time_type
- now.is_a?(Array) ? now[0..2] : Array(now).reverse[4..6]
+ now.is_a?(Array) ? now[0..2] : [now.year, now.month, now.day]
+ end
+
+ def current_time_in_zone(zone)
+ case zone
+ when :utc, :local
+ Time.now.send("get#{zone}")
+ when :current
+ Time.current
+ else
+ Time.use_zone(zone) { Time.current }
+ end
end
# Taken from ActiveSupport and simplified
def time_with_datetime_fallback(utc_or_local, year, month=1, day=1, hour=0, min=0, sec=0, usec=0)
return nil if hour > 23 || min > 59 || sec > 59