Class: Spree::Preferences::StoreInstance
- Inherits:
-
Object
- Object
- Spree::Preferences::StoreInstance
- Defined in:
- app/models/spree/preferences/store.rb
Direct Known Subclasses
Instance Attribute Summary collapse
-
#persistence ⇒ Object
Returns the value of attribute persistence.
Instance Method Summary collapse
- #clear_cache ⇒ Object
- #delete(key) ⇒ Object
- #exist?(key) ⇒ Boolean
- #get(key) ⇒ Object (also: #fetch)
-
#initialize ⇒ StoreInstance
constructor
A new instance of StoreInstance.
- #set(key, value) ⇒ Object (also: #[]=)
Constructor Details
#initialize ⇒ StoreInstance
Returns a new instance of StoreInstance.
21 22 23 24 |
# File 'app/models/spree/preferences/store.rb', line 21 def initialize @cache = Rails.cache @persistence = true end |
Instance Attribute Details
#persistence ⇒ Object
Returns the value of attribute persistence.
19 20 21 |
# File 'app/models/spree/preferences/store.rb', line 19 def persistence @persistence end |
Instance Method Details
#clear_cache ⇒ Object
74 75 76 |
# File 'app/models/spree/preferences/store.rb', line 74 def clear_cache @cache.clear end |
#delete(key) ⇒ Object
69 70 71 72 |
# File 'app/models/spree/preferences/store.rb', line 69 def delete(key) @cache.delete(key) destroy(key) end |
#exist?(key) ⇒ Boolean
32 33 34 35 |
# File 'app/models/spree/preferences/store.rb', line 32 def exist?(key) @cache.exist?(key) || should_persist? && Spree::Preference.where(key: key).exists? end |
#get(key) ⇒ Object Also known as: fetch
37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 |
# File 'app/models/spree/preferences/store.rb', line 37 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? val = if preference = Spree::Preference.find_by(key: key) # it does exist preference.value else # use the fallback value 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 |
#set(key, value) ⇒ Object Also known as: []=
26 27 28 29 |
# File 'app/models/spree/preferences/store.rb', line 26 def set(key, value) @cache.write(key, value) persist(key, value) end |