Class: Konfig::Option

Inherits:
OpenStruct
  • Object
show all
Includes:
Enumerable
Defined in:
lib/konfig/option.rb

Constant Summary collapse

SETTINGS_RESERVED_NAMES =
%w[select collect test count zip min max].freeze

Instance Method Summary collapse

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(method_name, *args) ⇒ Object

Raises:



61
62
63
64
65
# File 'lib/konfig/option.rb', line 61

def method_missing(method_name, *args)
  raise KeyError, "key not found: #{method_name.inspect}" unless key?(method_name) if method_name !~ /.*(?==\z)/m

  super
end

Instance Method Details

#[](param) ⇒ Object



52
53
54
55
# File 'lib/konfig/option.rb', line 52

def [](param)
  return super if SETTINGS_RESERVED_NAMES.include?(param)
  send("#{param}")
end

#[]=(param, value) ⇒ Object



57
58
59
# File 'lib/konfig/option.rb', line 57

def []=(param, value)
  send("#{param}=", value)
end

#empty?Boolean

Returns:

  • (Boolean)


11
12
13
# File 'lib/konfig/option.rb', line 11

def empty?
  marshal_dump.empty?
end

#generate_schema(start = nil) ⇒ Object



68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
# File 'lib/konfig/option.rb', line 68

def generate_schema(start = nil)
  start = self if start.nil?
  result = []
  start.table.each do |k, v|
    if v.is_a?(Option)
      result << "required(:#{k}).schema do"
      result << generate_schema(v)
      result << "end"
    elsif [String, Integer, Numeric, Array].include? v.class
      result << generate_required(k, v)
    elsif [TrueClass, FalseClass].include? v.class
      result << "required(:#{k}).filled(:bool)"
    elsif v.nil?
      result << "required(:#{k})"
    end
  end

  return result
end

#has_key?(key) ⇒ Boolean

Returns:

  • (Boolean)


25
26
27
# File 'lib/konfig/option.rb', line 25

def has_key?(key)
  table.has_key?(key)
end

#key?(key) ⇒ Boolean

Returns:

  • (Boolean)


21
22
23
# File 'lib/konfig/option.rb', line 21

def key?(key)
  table.key?(key)
end

#keysObject



7
8
9
# File 'lib/konfig/option.rb', line 7

def keys
  marshal_dump.keys
end

#load(h) ⇒ Object



15
16
17
18
19
# File 'lib/konfig/option.rb', line 15

def load(h)
  marshal_load(__convert(h).marshal_dump)
  validate!
  self
end

#validate!Object



29
30
31
32
33
34
35
36
37
38
39
40
41
42
# File 'lib/konfig/option.rb', line 29

def validate!
  if Konfig.configuration.schema
    v_res = Konfig.configuration.schema.(self.marshal_dump)

    unless v_res.success?
      error = Konfig::ValidationError.format(v_res)
      if Konfig.configuration.fail_on_validation
        raise Konfig::ValidationError.new("Config validation failed:\n\n#{error}")
      else
        Konfig.configuration.logger.error "Config validation failed:\n\n#{error}"
      end
    end
  end
end