Sha256: f415341adb54c2f4df285d6a9d2dc38fe98b1485b3f5020a29abe71c38dfa3af

Contents?: true

Size: 1013 Bytes

Versions: 3

Compression:

Stored size: 1013 Bytes

Contents

module UserPreferences
  class PreferenceDefinition
    attr_reader :name, :category

    def initialize(definition, category, name)
      @definition = definition
      @category = category
      @name = name
    end

    def permitted_values
      if binary?
        result = [false, true]
      else
        @definition[:values]
      end
    end

    def binary?
      !@definition.is_a?(Hash)
    end

    def default
      binary? ? @definition : @definition[:default]
    end

    def lookup(index)
      permitted_values[index] if index
    end

    def to_db(value)
      value = to_bool(value) if binary?
      permitted_values.index(value)
    end

    private

    def to_bool(value)
      return true if value == 1
      return true if value == true || value =~ (/^(true|t|yes|y|1)$/i)

      return false if value == 0
      return false if value == false || value.blank? || value =~ (/^(false|f|no|n|0)$/i)
      raise ArgumentError.new("invalid value for Boolean: \"#{value}\"")
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
user_preferences-1.0.2 lib/user_preferences/preference_definition.rb
user_preferences-1.0.1 lib/user_preferences/preference_definition.rb
user_preferences-1.0.0 lib/user_preferences/preference_definition.rb