Class: Clock

Inherits:
Object
  • Object
show all
Defined in:
lib/brut/junk_drawer.rb

Overview

Models a clock, which is a time in the context of a time zone. This theoretically makes it easier to get the time and date at the time zone of the user.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(tzinfo_timezone, now: nil) ⇒ Clock

Create a clock in the given timezone. If tzinfo_timezone is non-nil, that value is the time zone of the clock, and all Time instances returned will be in that time zone. If tzinfo_timezone is nil, then ENV["TZ"] is consulted. If the value of that environment variable is a valid timezone, it is used. Otherwise, UTC is used.

Parameters:

  • tzinfo_timezone (TZInfo::Timezone)

    if present, this is the timezone of the clock.

  • now (Time) (defaults to: nil)

    if omitted, uses Time.now when asked the current time. Otherwises, uses this value, as a Time for now. Don't do this unless you are testing.



12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
# File 'lib/brut/junk_drawer.rb', line 12

def initialize(tzinfo_timezone, now: nil)
  if tzinfo_timezone
    @timezone = tzinfo_timezone
  elsif ENV["TZ"]
    @timezone = begin
                  TZInfo::Timezone.get(ENV["TZ"])
                rescue TZInfo::InvalidTimezoneIdentifier => ex
                  Brut.container.instrumentation.record_exception(ex, class: self.class, invalid_env_tz: ENV['TZ'])
                  nil
                end
  end
  if @timezone.nil?
    @timezone = TZInfo::Timezone.get("UTC")
  end
  @now = now
end

Instance Attribute Details

#timezoneObject (readonly)

Returns the value of attribute timezone.



4
5
6
# File 'lib/brut/junk_drawer.rb', line 4

def timezone
  @timezone
end

Instance Method Details

#in_time_zone(time) ⇒ Time

Convert the given time to this clock's time zone

Parameters:

  • time (Time)

    a timestamp you wish to conver to this clock's time zone

Returns:

  • (Time)

    a new Time in the timezone of this clock.



48
49
50
# File 'lib/brut/junk_drawer.rb', line 48

def in_time_zone(time)
  @timezone.to_local(time)
end

#nowTime

Get the current time in the configured timezone, unless now: was used in the constructor, in which case that timestamp is returned in the configured time zone.

Returns:

  • (Time)

    the time now in the time zone of this clock



33
34
35
36
37
38
39
# File 'lib/brut/junk_drawer.rb', line 33

def now
  if @now
    self.in_time_zone(@now)
  else
    Time.now(in: @timezone)
  end
end

#todayObject



41
42
43
# File 'lib/brut/junk_drawer.rb', line 41

def today
  self.now.to_date
end