Module: Time::NoBrainerExtensions

Included in:
Time
Defined in:
lib/no_brainer/document/types/time.rb

Constant Summary collapse

InvalidType =
NoBrainer::Error::InvalidType

Instance Method Summary collapse

Instance Method Details

#nobrainer_cast_db_to_model(value) ⇒ Object



23
24
25
26
# File 'lib/no_brainer/document/types/time.rb', line 23

def nobrainer_cast_db_to_model(value)
  return value unless value.is_a?(Time)
  nobrainer_timezoned(NoBrainer::Config.user_timezone, value)
end

#nobrainer_cast_model_to_db(value) ⇒ Object



28
29
30
31
# File 'lib/no_brainer/document/types/time.rb', line 28

def nobrainer_cast_model_to_db(value)
  return value unless value.is_a?(Time)
  nobrainer_timezoned(NoBrainer::Config.db_timezone, value)
end

#nobrainer_cast_user_to_model(value) ⇒ Object



7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
# File 'lib/no_brainer/document/types/time.rb', line 7

def nobrainer_cast_user_to_model(value)
  case value
  when Time then time = value
  when String
    value = value.strip
    value = value.sub(/Z$/, '+00:00') unless NoBrainer.jruby?
    # Using DateTime to preserve the timezone offset
    dt = DateTime.parse(value) rescue (raise InvalidType)
    time = Time.new(dt.year, dt.month, dt.day, dt.hour, dt.minute, dt.second, dt.zone)
    raise InvalidType unless time.iso8601 == value
  else raise InvalidType
  end

  nobrainer_timezoned(NoBrainer::Config.user_timezone, time)
end

#nobrainer_timezoned(tz, value) ⇒ Object



33
34
35
36
37
38
39
# File 'lib/no_brainer/document/types/time.rb', line 33

def nobrainer_timezoned(tz, value)
  case tz
  when :local     then value.getlocal
  when :utc       then value.getutc
  when :unchanged then value
  end
end