Class: FreshObjects::Lookup

Inherits:
Object
  • Object
show all
Defined in:
lib/fresh_objects/lookup.rb

Overview

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.

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(timestamps_by_id = {}) ⇒ Lookup

Returns a new instance of Lookup.



28
29
30
31
32
33
34
# 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

Instance Attribute Details

#timestamps_by_idObject (readonly)

Returns the value of attribute timestamps_by_id.



26
27
28
# File 'lib/fresh_objects/lookup.rb', line 26

def timestamps_by_id
  @timestamps_by_id
end

Class Method Details

.make(timestamps_by_id = {}) ⇒ Object



17
18
19
20
21
22
23
# 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

Instance Method Details

#==(other) ⇒ Object Also known as: eql?



62
63
64
# File 'lib/fresh_objects/lookup.rb', line 62

def ==(other)
  other.is_a?(self.class) && timestamps_by_id == other.timestamps_by_id
end

#fresh?(id, timestamp) ⇒ Boolean

Returns:

  • (Boolean)


42
43
44
# File 'lib/fresh_objects/lookup.rb', line 42

def fresh?(id, timestamp)
  !stale?(id, timestamp)
end

#fresh_set?(id, timestamp) ⇒ Boolean

Returns:

  • (Boolean)


36
37
38
39
40
# 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) ⇒ Object



54
55
56
# File 'lib/fresh_objects/lookup.rb', line 54

def get(id)
  timestamps_by_id[id.to_s]
end

#set(id, timestamp) ⇒ Object



58
59
60
# 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) ⇒ Boolean

Returns:

  • (Boolean)


46
47
48
49
50
51
52
# 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