Class: Formica::Config

Inherits:
Object
  • Object
show all
Defined in:
lib/formica.rb

Defined Under Namespace

Classes: Option

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(values = {}) ⇒ Config

Returns a new instance of Config.



40
41
42
43
# File 'lib/formica.rb', line 40

def initialize(values = {})
  @options = self.class.options.map { |n, o| [n, Option.new(o, false)] }.to_h
  update!(values)
end

Class Method Details

.validate_dependencies!Object



58
59
60
61
62
63
64
65
66
# File 'lib/formica.rb', line 58

def self.validate_dependencies!
  require 'tsort'

  each_node = ->(&b) { options.each_key(&b) }
  each_child = ->(n, &b) { options[n].depends_on.each(&b) }
  TSort.tsort each_node, each_child
rescue TSort::Cyclic => e
  raise "Some options have a circular dependency: #{e}"
end

Instance Method Details

#force!Object



53
54
55
56
# File 'lib/formica.rb', line 53

def force!
  @options.each { |_, o| public_send(o.option.attr_name) }
  self
end

#to_hObject



49
50
51
# File 'lib/formica.rb', line 49

def to_h
  Hash[@options.map { |_, o| [o.option.attr_name, o.value] if o.defined }.compact]
end

#to_sObject



45
46
47
# File 'lib/formica.rb', line 45

def to_s
  "<#{self.class} #{to_h}>"
end

#update!(values) ⇒ Object



72
73
74
75
76
77
78
79
# File 'lib/formica.rb', line 72

def update!(values)
  values.each do |k, v|
    option = @options[k] || raise(KeyError, "No option `#{k}` in #{self}")
    v = option.validate!(v, self)
    option.defined = true
    option.value = v
  end
end

#with_changes(changes) ⇒ Object



68
69
70
# File 'lib/formica.rb', line 68

def with_changes(changes)
  self.class.new(**to_h.merge(changes))
end