Class: Restforce::DB::AssociationCache

Inherits:
Object
  • Object
show all
Defined in:
lib/restforce/db/association_cache.rb

Overview

Restforce::DB::AssociationCache stores a set of constructed database association records, providing utilities to fetch unpersisted records which match a specific set of Salesforce lookups.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(record = nil) ⇒ AssociationCache

Public: Initialize a new Restforce::DB::AssociationCache.

record - An instance of ActiveRecord::Base (optional).



15
16
17
18
# File 'lib/restforce/db/association_cache.rb', line 15

def initialize(record = nil)
  @cache = Hash.new { |h, k| h[k] = [] }
  self << record if record
end

Instance Attribute Details

#cacheObject (readonly)

Returns the value of attribute cache.



10
11
12
# File 'lib/restforce/db/association_cache.rb', line 10

def cache
  @cache
end

Instance Method Details

#<<(record) ⇒ Object

Public: Add a record to the cache.

record - An instance of ActiveRecord::Base.

Returns nothing.



25
26
27
# File 'lib/restforce/db/association_cache.rb', line 25

def <<(record)
  @cache[record.class] << record
end

#find(database_model, lookups) ⇒ Object

Public: Find an existing record with the given lookup values.

database_model - A subclass of ActiveRecord::Base. lookups - A Hash mapping database columns to Salesforce IDs.

Returns an instance of ActiveRecord::Base or nil.



35
36
37
38
39
40
41
42
43
44
45
46
# File 'lib/restforce/db/association_cache.rb', line 35

def find(database_model, lookups)
  record = @cache[database_model].detect do |cached|
    lookups.all? { |column, value| cached.send(column) == value }
  end

  return record if record

  record = database_model.find_by(lookups)
  self << record if record

  record
end