Module: ArCache::Marshal

Included in:
Table
Defined in:
lib/ar_cache/marshal.rb

Instance Method Summary collapse

Instance Method Details

#delete(*ids) ⇒ Object



5
6
7
8
9
# File 'lib/ar_cache/marshal.rb', line 5

def delete(*ids)
  return -1 if disabled?

  ArCache::Store.delete_multi(ids.map { |id| primary_cache_key(id) })
end

#read(where_clause, select_values, &block) ⇒ Object



37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
# File 'lib/ar_cache/marshal.rb', line 37

def read(where_clause, select_values, &block)
  entries_hash = ArCache::Store.read_multi(where_clause.cache_hash.keys)
  where_clause.cache_hash.each_key { |k| where_clause.add_missed_values(k) unless entries_hash.key?(k) }

  records = []

  entries_hash.each do |k, entry|
    entry = entry.slice(*select_values) if select_values
    wrong_key = detect_wrong_key(entry, where_clause.to_h)

    if wrong_key
      where_clause.add_missed_values(k)
      where_clause.add_invalid_keys(k) if column_indexes.include?(wrong_key)
    else
      records << instantiate(where_clause.klass, entry, &block)
    end
  end

  where_clause.delete_invalid_keys

  records
end

#write(records) ⇒ Object

WARNING:

In order to ensure that the written data is consistent with the database,
only the record from the query can be written.


14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# File 'lib/ar_cache/marshal.rb', line 14

def write(records)
  return -1 if disabled?

  cache_hash = {}
  records.each do |record|
    attributes = record.attributes_before_type_cast
    key = nil

    unique_indexes.each_with_index do |index, i|
      if i.zero? # is primary key
        key = primary_cache_key(attributes[primary_key])
        cache_hash[key] = attributes
      else
        cache_hash[cache_key(attributes, index)] = key
      end
    end
  end

  ArCache::Store.write_multi(cache_hash)
rescue Encoding::UndefinedConversionError
  0
end