Class: Clock
- Inherits:
-
Object
- Object
- Clock
- 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
-
#timezone ⇒ Object
readonly
Returns the value of attribute timezone.
Instance Method Summary collapse
-
#in_time_zone(time) ⇒ Time
Convert the given time to this clock's time zone.
-
#initialize(tzinfo_timezone, now: nil) ⇒ Clock
constructor
Create a clock in the given timezone.
-
#now ⇒ Time
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. -
#today ⇒ Object
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.
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
#timezone ⇒ Object (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
48 49 50 |
# File 'lib/brut/junk_drawer.rb', line 48 def in_time_zone(time) @timezone.to_local(time) end |
#now ⇒ Time
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.
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 |
#today ⇒ Object
41 42 43 |
# File 'lib/brut/junk_drawer.rb', line 41 def today self.now.to_date end |