Module: Druthers::Support::ClassMethods

Defined in:
lib/druthers/support.rb

Instance Method Summary collapse

Instance Method Details

#druthers_cacheObject

This can be overridden by the consumer



17
18
19
# File 'lib/druthers/support.rb', line 17

def druthers_cache
  @druthers_cache ||= ActiveSupport::Cache::MemoryStore.new(expires_in: 10.minutes)
end

#get_druther(key) ⇒ Object

Directly access the setting with the given key name. Note that overriding this method shouldn’t be done directly. Use one of the event methods instead.



24
25
26
27
28
29
# File 'lib/druthers/support.rb', line 24

def get_druther(key)
  druthers_cache.fetch(key) do
    val = where(key: key).pluck(:value).to_a
    val.present? ? val.first : send_druthers_event(:default, key)
  end
end

#send_druthers_event(event_name, key) ⇒ Object



48
49
50
51
# File 'lib/druthers/support.rb', line 48

def send_druthers_event(event_name, key)
  sym = "#{event_name}_#{key}".to_sym
  send(sym) if respond_to?(sym)
end

#set_druther(key, value) ⇒ Object



31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
# File 'lib/druthers/support.rb', line 31

def set_druther(key, value)
  obj = where(key: key).first_or_initialize
  if obj.respond_to? :update!
    # Rails 4.x:
    obj.update!(value: value)
  else
    # Rails 3.x:
    obj.update_attributes!(value: value)
  end
  # Only update the cache if the update! succeeded:
  # Note that we cached the obj.value, rather than the value, to make sure
  # returned values are consistent with the serializer's result.
  # See https://github.com/mceachen/druthers/pull/2
  druthers_cache.write(key, obj.value)
  obj
end