Sha256: ae8f7b6da5906925369f5d52046205165dbc8ec343ae6870458010bb02abced6

Contents?: true

Size: 1.91 KB

Versions: 10

Compression:

Stored size: 1.91 KB

Contents

require 'ostruct'

module Tienda
  class Setting < ActiveRecord::Base

    # Validations
    validates :key, :presence => true, :uniqueness => true
    validates :value, :presence => true
    validates :value_type, :presence => true

    before_validation do
      self.value_type = I18n.t("tienda.settings.types")[self.key.to_sym].try(:capitalize) || self.value.class.to_s
      self.value      = encoded_value
    end

    # The encoded value for saving in the backend (as a string)
    #
    # @return [String]
    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

    # The decoded value for the setting attribute (in it's native type)
    #
    # @return [Object]
    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

    # A full hash of all settings available in the current scope
    #
    # @return [Hash]
    def self.to_hash
      all.inject({}) do |h, setting|
        h[setting.key.to_s] = setting.decoded_value
        h
      end
    end

    # Update settings from a given hash and persist them. Accepts a
    # hash of keys (which should be strings).
    #
    # @return [Hash]
    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

  end
end

Version data entries

10 entries across 10 versions & 1 rubygems

Version Path
tienda-2.1.3 app/models/tienda/setting.rb
tienda-2.1.2 app/models/tienda/setting.rb
tienda-2.1.1 app/models/tienda/setting.rb
tienda-2.1.0 app/models/tienda/setting.rb
tienda-2.0.2 app/models/tienda/setting.rb
tienda-2.0.1 app/models/tienda/setting.rb
tienda-1.1.2 app/models/tienda/setting.rb
tienda-1.1.1 app/models/tienda/setting.rb
tienda-1.1.0 app/models/tienda/setting.rb
tienda-1.0.0 app/models/tienda/setting.rb