Sha256: 7689b644fd4dbd3b8d55ae54df425320a65e8d6cc14c320cdee630a079166964

Contents?: true

Size: 1.44 KB

Versions: 7

Compression:

Stored size: 1.44 KB

Contents

module NsSettingsUi
  class Setting < ActiveRecord::Base
    TYPES = {
      string: 1,
      integer: 2,
      boolean: 3,
      date: 7,
      nullable_string: 4,
      nullable_integer: 5,
      nullable_boolean: 6
    }.freeze

    TYPE_HANDLERS = {
      1 => :string_value,
      2 => :integer_value,
      3 => :boolean_value,
      7 => :date_value,
      4 => :nullable_string,
      5 => :nullable_integer,
      6 => :nullable_boolean
    }.freeze

    NULL_VALUES = [nil, ''].freeze

    # TODO: in Nttr
    # belongs_to :country
    #
    # def self.get(country, *keys)
    #   where(country: country, key: keys.join('.')).first_or_create
    # end
    #
    # def country_code
    #   country.try(:alpha2).to_s
    # end

    def self.get(*keys)
      where(key: keys.join('.')).first_or_create
    end

    def keys
      key.split('.').map(&:to_sym)
    end

    def formatted_value
      TYPE_HANDLERS[value_type] ? send(TYPE_HANDLERS[value_type]) : value
    end

    private

    def nullify?
      NULL_VALUES.include?(value)
    end

    def nullable_string
      string_value unless nullify?
    end

    def nullable_integer
      integer_value unless nullify?
    end

    def nullable_boolean
      boolean_value unless nullify?
    end

    def string_value
      value.to_s
    end

    def integer_value
      value.to_i
    end

    def boolean_value
      value == 'true'
    end

    def date_value
      Date.parse(value)
    end
  end
end

Version data entries

7 entries across 7 versions & 1 rubygems

Version Path
ns_settings_ui-1.7.0 app/models/ns_settings_ui/setting.rb
ns_settings_ui-1.6.1 app/models/ns_settings_ui/setting.rb
ns_settings_ui-1.6.0 app/models/ns_settings_ui/setting.rb
ns_settings_ui-1.5.3 app/models/ns_settings_ui/setting.rb
ns_settings_ui-1.5.2 app/models/ns_settings_ui/setting.rb
ns_settings_ui-1.5.1 app/models/ns_settings_ui/setting.rb
ns_settings_ui-1.4.0 app/models/ns_settings_ui/setting.rb