Class: FreshObjects::Filter

Inherits:
Object
  • Object
show all
Extended by:
Forwardable
Includes:
Enumerable
Defined in:
lib/fresh_objects/filter.rb

Overview

This class can do a “row/timestamp-based semantic merge”. In other words: you can use this class to dump any number of arrays of objects into and it will sift through them and only keep the latest, non-stale copies of the objects.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(lookup: {}, id_key: :id, timestamp_key: nil, resolver: Objectable.resolver) ⇒ Filter

Returns a new instance of Filter.



29
30
31
32
33
34
35
# File 'lib/fresh_objects/filter.rb', line 29

def initialize(lookup: {}, id_key: :id, timestamp_key: nil, resolver: Objectable.resolver)
  @lookup        = Lookup.make(lookup)
  @id_key        = id_key
  @timestamp_key = timestamp_key
  @resolver      = resolver
  @objects_by_id = {}
end

Instance Attribute Details

#id_keyObject (readonly)

Returns the value of attribute id_key.



20
21
22
# File 'lib/fresh_objects/filter.rb', line 20

def id_key
  @id_key
end

#lookupObject (readonly)

Returns the value of attribute lookup.



20
21
22
# File 'lib/fresh_objects/filter.rb', line 20

def lookup
  @lookup
end

#resolverObject (readonly)

Returns the value of attribute resolver.



20
21
22
# File 'lib/fresh_objects/filter.rb', line 20

def resolver
  @resolver
end

#timestamp_keyObject (readonly)

Returns the value of attribute timestamp_key.



20
21
22
# File 'lib/fresh_objects/filter.rb', line 20

def timestamp_key
  @timestamp_key
end

Instance Method Details

#add(object, default_timestamp: Time.now.utc) ⇒ Object



41
42
43
44
45
46
47
48
# File 'lib/fresh_objects/filter.rb', line 41

def add(object, default_timestamp: Time.now.utc)
  id        = resolver.get(object, id_key).to_s
  timestamp = resolve_timestamp(object, default_timestamp)

  objects_by_id[id] = object if lookup.fresh_set?(id, timestamp)

  self
end

#add_each(objects, default_timestamp: Time.now.utc) ⇒ Object



37
38
39
# File 'lib/fresh_objects/filter.rb', line 37

def add_each(objects, default_timestamp: Time.now.utc)
  tap { objects.each { |o| add(o, default_timestamp: default_timestamp) } }
end