Module: Ensurance::TimeEnsure::ClassMethods

Defined in:
lib/ensurance/time_ensure.rb

Instance Method Summary collapse

Instance Method Details

#ensure(thing) ⇒ Object



13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
# File 'lib/ensurance/time_ensure.rb', line 13

def ensure(thing)
  ::Time.zone ||= "UTC"

  case thing.class.name
  when 'NilClass', 'Time'
    thing
  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.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
      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

#ensure!(thing) ⇒ Object

Raises:

  • (ArgumentError)


48
49
50
51
52
# File 'lib/ensurance/time_ensure.rb', line 48

def ensure!(thing)
  result = self.ensure(thing)
  raise ArgumentError, "Cannot Time.ensure(#{thing})" unless result
  result
end