class KingKonf::Variable

Attributes

allowed_values[R]
default[R]
description[R]
name[R]
options[R]
type[R]
validate_with[R]

Public Class Methods

new(name:, type:, default: nil, description: "", required: false, allowed_values: nil, validate_with: ->(_) { true } click to toggle source
# File lib/king_konf/variable.rb, line 7
def initialize(name:, type:, default: nil, description: "", required: false, allowed_values: nil, validate_with: ->(_) { true }, options: {})
  @name, @type = name, type
  @description = description
  @required = required
  @allowed_values = allowed_values
  @options = options
  @default = cast(default) unless default.nil?
  @validate_with = validate_with
end

Public Instance Methods

allowed?(value) click to toggle source
# File lib/king_konf/variable.rb, line 42
def allowed?(value)
  allowed_values.nil? || allowed_values.include?(cast(value))
rescue ConfigError
  false
end
cast(value) click to toggle source
# File lib/king_konf/variable.rb, line 17
def cast(value)
  case @type
  when :boolean then [true, false].include?(value) ? value : Decoder.boolean(value, **options)
  when :integer then Integer(value)
  when :float then Float(value)
  when :duration then value.is_a?(Integer) ? value : Decoder.duration(value)
  when :symbol then value.to_sym
  else value
  end
rescue ArgumentError, NoMethodError
  raise ConfigError, "invalid value #{value.inspect} for variable `#{name}`, expected #{type}"
end
decode(value) click to toggle source
# File lib/king_konf/variable.rb, line 48
def decode(value)
  Decoder.public_send(@type, value, **options)
end
required?() click to toggle source
# File lib/king_konf/variable.rb, line 30
def required?
  @required
end
valid?(value) click to toggle source
# File lib/king_konf/variable.rb, line 34
def valid?(value)
  cast_value = cast(value)
rescue ConfigError
  false
else
  !!validate_with.call(cast_value)
end