Class: ArStore

Inherits:
ApplicationRecord
  • Object
show all
Defined in:
app/models/ar_store.rb

Constant Summary collapse

VALID_OPTION_KEYS =
[:expires_in]

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.cleanObject



43
44
45
# File 'app/models/ar_store.rb', line 43

def self.clean
  where(expired_conditions).delete_all
end

.expirationObject



8
9
10
# File 'app/models/ar_store.rb', line 8

def self.expiration
  @expiration ||= 1.day
end

.expiration=(seconds) ⇒ Object



4
5
6
# File 'app/models/ar_store.rb', line 4

def self.expiration=(seconds)
  @expiration ||= sections
end

.expired_conditionsObject



47
48
49
# File 'app/models/ar_store.rb', line 47

def self.expired_conditions
  "now() > (updated_at + (expires * '1 second'::interval))"
end

.fetch(key, value = nil, options = {}, &blk) ⇒ Object

Raises:

  • (ArgumentError)


36
37
38
39
40
41
# File 'app/models/ar_store.rb', line 36

def self.fetch(key, value = nil, options = {}, &blk)
  options.symbolize_keys!
  raise ArgumentError "expires_in is the only valid option" if invalid_options(options).present?
  raise ArgumentError, "Pass value or a block, not both" if value && block_given?
  read(key) || new.write!(key, (value.nil? ? yield : value), options[:expires_in])
end

.invalid_options(opts) ⇒ Object



25
26
27
# File 'app/models/ar_store.rb', line 25

def self.invalid_options(opts)
  opts.keys - VALID_OPTION_KEYS
end

.read(key) ⇒ Object



20
21
22
23
# File 'app/models/ar_store.rb', line 20

def self.read(key)
  r = get(key).try(:value)
  r ? Marshal.load(r) : nil
end

.write(key, value = nil, options = {}, &blk) ⇒ Object

Raises:

  • (ArgumentError)


29
30
31
32
33
34
# File 'app/models/ar_store.rb', line 29

def self.write(key, value = nil, options = {},  &blk)
  options.symbolize_keys!
  raise ArgumentError "expires_in is the only valid option" if invalid_options(options).present?
  raise ArgumentError, "Pass value or a block, not both" if value && block_given?
  (get(key) || new).write!(key, (value.nil? ? yield : value), options[:expires_in])
end

Instance Method Details

#write!(key, val, expires = nil) ⇒ Object



12
13
14
15
16
17
18
# File 'app/models/ar_store.rb', line 12

def write!(key, val, expires = nil)
  self.key     = key
  self.value   = Marshal.dump(val)
  self.expires = expires
  self.save!
  val
end