class FreshObjects::Filter

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.

Attributes

id_key[R]
lookup[R]
objects_by_id[R]
resolver[R]
timestamp_key[R]

Public Class Methods

new(lookup: {}, id_key: :id, timestamp_key: nil, resolver: Objectable.resolver) click to toggle source
# 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

Public Instance Methods

add(object, default_timestamp: Time.now.utc) click to toggle source
# 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) click to toggle source
# 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

Private Instance Methods

objects() click to toggle source
# File lib/fresh_objects/filter.rb, line 54
def objects
  objects_by_id.values
end
resolve_timestamp(object, default_timestamp) click to toggle source
# File lib/fresh_objects/filter.rb, line 58
def resolve_timestamp(object, default_timestamp)
  # If we have a timestamp key then lets try and get it from the record.
  # If we don't then we can defer to the default.
  retrieved = timestamp_key ? resolver.get(object, timestamp_key) : default_timestamp

  # One last check, just in case the record returned back something "null-like" like a blank
  # string, lets treat that as nil.
  return default_timestamp if retrieved.to_s.empty?

  retrieved
end