Class: Shoppe::Setting

Inherits:
ActiveRecord::Base
  • Object
show all
Defined in:
app/models/shoppe/setting.rb

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.to_hashHash

A full hash of all settings available in the current scope

Returns:

  • (Hash)


43
44
45
46
47
48
# File 'app/models/shoppe/setting.rb', line 43

def self.to_hash
  all.inject({}) do |h, setting|
    h[setting.key.to_s] = setting.decoded_value
    h
  end
end

.update_from_hash(hash) ⇒ Hash

Update settings from a given hash and persist them. Accepts a hash of keys (which should be strings).

Returns:

  • (Hash)


54
55
56
57
58
59
60
61
62
63
64
65
# File 'app/models/shoppe/setting.rb', line 54

def self.update_from_hash(hash)
  existing_settings = self.all.to_a
  hash.each do |key, value|
    existing = existing_settings.select { |s| s.key.to_s == key.to_s }.first
    if existing
      value.blank? ? existing.destroy! : existing.update!(value: value)
    else
      value.blank? ? nil : self.create!(key: key, value: value)
    end
  end
  hash
end

Instance Method Details

#decoded_valueObject

The decoded value for the setting attribute (in it’s native type)

Returns:

  • (Object)


30
31
32
33
34
35
36
37
38
# File 'app/models/shoppe/setting.rb', line 30

def decoded_value
  case value_type
  when 'Fixnum'         then  value.to_i
  when 'Float'          then  value.to_f
  when 'Array', 'Hash'  then  JSON.parse(value)
  when 'Boolean'        then  value == 'true' ? true : false
  else                        value.to_s
  end
end

#encoded_valueString

The encoded value for saving in the backend (as a string)

Returns:

  • (String)


19
20
21
22
23
24
25
# File 'app/models/shoppe/setting.rb', line 19

def encoded_value
  case value_type
  when 'Array', 'Hash'  then  value.to_json
  when 'Boolean'        then  value.to_s == 'true' ? 'true' : 'false'
  else                        value.to_s
  end
end