class FreshObjects::Lookup

A data structure which holds a timestamp per ID. It can then be used as a performant lookup to see if an incoming timestamp is stale or new. It is essentially backed by a hash where the key is a string and the value is a Time object. You can also pass in a hash into the constructor for configuration ease.

Attributes

timestamps_by_id[R]

Public Class Methods

make(timestamps_by_id = {}) click to toggle source
# File lib/fresh_objects/lookup.rb, line 17
def make(timestamps_by_id = {})
  if timestamps_by_id.is_a?(self)
    timestamps_by_id
  else
    new(timestamps_by_id)
  end
end
new(timestamps_by_id = {}) click to toggle source
# File lib/fresh_objects/lookup.rb, line 28
def initialize(timestamps_by_id = {})
  @timestamps_by_id = timestamps_by_id.map do |id, timestamp|
    [id.to_s, parse_time(timestamp)]
  end.to_h

  freeze
end

Public Instance Methods

==(other) click to toggle source
# File lib/fresh_objects/lookup.rb, line 62
def ==(other)
  other.is_a?(self.class) && timestamps_by_id == other.timestamps_by_id
end
Also aliased as: eql?
eql?(other)
Alias for: ==
fresh?(id, timestamp) click to toggle source
# File lib/fresh_objects/lookup.rb, line 42
def fresh?(id, timestamp)
  !stale?(id, timestamp)
end
fresh_set?(id, timestamp) click to toggle source
# File lib/fresh_objects/lookup.rb, line 36
def fresh_set?(id, timestamp)
  fresh?(id, timestamp).tap do |fresh|
    set(id, timestamp) if fresh
  end
end
get(id) click to toggle source
# File lib/fresh_objects/lookup.rb, line 54
def get(id)
  timestamps_by_id[id.to_s]
end
set(id, timestamp) click to toggle source
# File lib/fresh_objects/lookup.rb, line 58
def set(id, timestamp)
  tap { timestamps_by_id[id.to_s] = parse_time(timestamp) }
end
stale?(id, timestamp) click to toggle source
# File lib/fresh_objects/lookup.rb, line 46
def stale?(id, timestamp)
  id        = id.to_s
  current   = get(id)
  timestamp = parse_time(timestamp)

  current && timestamp <= current
end

Private Instance Methods

parse_time(time) click to toggle source
# File lib/fresh_objects/lookup.rb, line 69
def parse_time(time)
  time.is_a?(Time) ? time : Time.parse(time.to_s).utc
end