Class: IdentityCache::Cached::AttributeByOne

Inherits:
Attribute
  • Object
show all
Defined in:
lib/identity_cache/cached/attribute_by_one.rb

Instance Attribute Summary collapse

Attributes inherited from Attribute

#alias_name, #key_fields, #model, #unique

Instance Method Summary collapse

Methods inherited from Attribute

#attribute, #cache_key, #expire, #fetch, #load_one_from_db

Constructor Details

#initializeAttributeByOne

Returns a new instance of AttributeByOne.



8
9
10
11
# File 'lib/identity_cache/cached/attribute_by_one.rb', line 8

def initialize(*)
  super
  @key_field = key_fields.first
end

Instance Attribute Details

#key_fieldObject (readonly)

Returns the value of attribute key_field.



6
7
8
# File 'lib/identity_cache/cached/attribute_by_one.rb', line 6

def key_field
  @key_field
end

Instance Method Details

#buildObject



13
14
15
16
17
18
19
20
21
22
23
24
25
# File 'lib/identity_cache/cached/attribute_by_one.rb', line 13

def build
  cached_attribute = self

  model.define_singleton_method(:"fetch_#{fetch_method_suffix}") do |key|
    raise_if_scoped
    cached_attribute.fetch(key)
  end

  model.define_singleton_method(:"fetch_multi_#{fetch_method_suffix}") do |keys|
    raise_if_scoped
    cached_attribute.fetch_multi(keys)
  end
end

#cache_encode(db_value) ⇒ Object Also known as: cache_decode



62
63
64
# File 'lib/identity_cache/cached/attribute_by_one.rb', line 62

def cache_encode(db_value)
  db_value
end

#fetch_multi(keys) ⇒ Object



27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
# File 'lib/identity_cache/cached/attribute_by_one.rb', line 27

def fetch_multi(keys)
  keys = keys.map { |key| cast_db_key(key) }

  unless model.should_use_cache?
    return load_multi_from_db(keys)
  end

  unordered_hash = CacheKeyLoader.load_multi(self, keys)

  # Calling `values` on the result is expected to return the values in the same order as their
  # corresponding keys. The fetch_multi_by_#{field_list} generated methods depend on this.
  ordered_hash = {}
  keys.each { |key| ordered_hash[key] = unordered_hash.fetch(key) }
  ordered_hash
end

#load_multi_from_db(keys) ⇒ Object



43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
# File 'lib/identity_cache/cached/attribute_by_one.rb', line 43

def load_multi_from_db(keys)
  rows = model.reorder(nil).where(load_from_db_where_conditions(keys)).pluck(key_field, attribute)
  result = {}
  default = unique ? nil : []
  keys.each do |index_value|
    result[index_value] = default.try!(:dup)
  end
  if unique
    rows.each do |index_value, attribute_value|
      result[index_value] = attribute_value
    end
  else
    rows.each do |index_value, attribute_value|
      result[index_value] << attribute_value
    end
  end
  result
end