lib/ensurance/time_ensure.rb in ensurance-0.1.26 vs lib/ensurance/time_ensure.rb in ensurance-0.1.27

- old
+ new

@@ -12,44 +12,44 @@ module ClassMethods def ensure(thing) ::Time.zone ||= "UTC" case thing.class.name - when 'NilClass' + when 'NilClass', 'Time' thing - when 'Time' - thing - when 'Date' - thing.beginning_of_day - when 'Integer', 'Float' - if thing.to_i.to_s == thing.to_s - dec = thing.to_s.size - 10 - thing /= (10 ** dec).to_f if dec > 0 + when "Integer" + if thing < 10 ** 10 + ::Time.zone.at(thing) + else # assume millis + ::Time.zone.at(thing / 1000.0) end + when "Float" ::Time.zone.at(thing) when 'String' - if thing.to_i.to_s == thing - ::Time.ensure(thing.to_i) - elsif thing.to_f.to_s == thing - ::Time.zone.at(thing.to_f) + if thing.match?(/\d{2}:\d{2}/) || thing.match?(/^\d{4}-\d{2}-\d{2}$/) + ::Time.parse(thing) + elsif thing.match?(/^\d+\.\d+$/) + self.ensure(thing.to_f) + elsif thing.match?(/^\d+$/) + self.ensure(thing.to_i) + elsif thing.blank? + nil else - ::Time.zone.parse(thing) + raise ArgumentError, "Cannot convert #{thing.class}/\"#{thing}\" to Time" end else if thing.respond_to?(:to_time) thing.to_time else raise ArgumentError, "Unhandled Type for Time to ensure: #{thing.class}" end end end - def ensure!(_thing) - def ensure!(thing) - result = self.ensure(thing) - raise ArgumentError, "Cannot Time.ensure(#{thing})" unless result - result - end + def ensure!(thing) + result = self.ensure(thing) + raise ArgumentError, "Cannot Time.ensure(#{thing})" unless result + result end end end end