Class: Spree::Preferences::StoreInstance

Inherits:
Object
  • Object
show all
Defined in:
app/models/spree/preferences/store.rb

Direct Known Subclasses

Store

Instance Method Summary (collapse)

Constructor Details

- (StoreInstance) initialize

Returns a new instance of StoreInstance



8
9
10
# File 'app/models/spree/preferences/store.rb', line 8

def initialize
  @cache = Rails.cache
end

Instance Method Details

- (Object) clear_cache



60
61
62
# File 'app/models/spree/preferences/store.rb', line 60

def clear_cache
  @cache.clear
end

- (Object) delete(key)



55
56
57
58
# File 'app/models/spree/preferences/store.rb', line 55

def delete(key)
  @cache.delete(key)
  destroy(key)
end

- (Boolean) exist?(key)

Returns:

  • (Boolean)


18
19
20
21
# File 'app/models/spree/preferences/store.rb', line 18

def exist?(key)
  @cache.exist?(key) ||
    should_persist? && Spree::Preference.where(key: key).exists?
end

- (Object) get(key) Also known as: fetch



23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
# File 'app/models/spree/preferences/store.rb', line 23

def get(key)
  # return the retrieved value, if it's in the cache
  # use unless nil? incase the value is actually boolean false
  #
  unless (val = @cache.read(key)).nil?
    return val
  end

  if should_persist?
    # If it's not in the cache, maybe it's in the database, but
    # has been cleared from the cache

    # does it exist in the database?
    if preference = Spree::Preference.find_by_key(key)
      # it does exist
      val = preference.value
    else
      # use the fallback value
      val = yield
    end

    # Cache either the value from the db or the fallback value.
    # This avoids hitting the db with subsequent queries.
    @cache.write(key, val)

    return val
  else
    yield
  end
end

- (Object) set(key, value) Also known as: []=



12
13
14
15
# File 'app/models/spree/preferences/store.rb', line 12

def set(key, value)
  @cache.write(key, value)
  persist(key, value)
end