Module: Configru

Defined in:
lib/configru.rb,
lib/configru/dsl.rb,
lib/configru/option.rb,
lib/configru/version.rb,
lib/configru/structhash.rb

Defined Under Namespace

Modules: DSL, OptionMethods Classes: Option, OptionArray, OptionError, OptionRequiredError, OptionTypeError, OptionValidationError, RequiredOption, StructHash

Constant Summary collapse

VERSION =
"3.3.1"

Class Method Summary collapse

Class Method Details

.[](key) ⇒ Object



105
106
107
# File 'lib/configru.rb', line 105

def self.[](key)
  @root[key]
end

.load(*files, &block) ⇒ Object



36
37
38
39
40
41
# File 'lib/configru.rb', line 36

def self.load(*files, &block)
  @files = files.flatten
  @options = DSL::OptionGroup.new(&block).options
  @root = StructHash.new
  self.reload
end

.load_file(file) ⇒ Object



59
60
61
62
# File 'lib/configru.rb', line 59

def self.load_file(file)
  @option_path = []
  self.load_group(@options, @root, YAML.load_file(file) || {})
end

.load_group(option_group, output, input) ⇒ Object



64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
# File 'lib/configru.rb', line 64

def self.load_group(option_group, output, input)
  option_group.each do |key, option|
    @option_path << key

    # option is a group
    if option.is_a? Hash
      if input.has_key?(key) && !input[key].is_a?(Hash)
        raise OptionTypeError.new(@option_path, Hash, input[key].class)
      end
      group_output = output[key] || StructHash.new
      self.load_group(option, group_output, input[key] || {})
      output[key] = group_output
      @option_path.pop
      next
    end

    if input.include? key
      value = input[key]
    elsif output.include? key # option has already been set
      @option_path.pop
      next
    elsif option.is_a? RequiredOption
      raise OptionRequiredError.new(@option_path)
    else # option has not been set
      value = option.default
    end

    unless option.type?(value)
      raise OptionTypeError.new(@option_path, option.type, value.class)
    end

    unless option.valid?(value)
      raise OptionValidationError.new(@option_path, option.validation)
    end

    output[key] = option.transform(value)

    @option_path.pop
  end
end

.method_missing(method, *args) ⇒ Object



109
110
111
# File 'lib/configru.rb', line 109

def self.method_missing(method, *args)
  @root.send(method, *args)
end

.reloadObject



43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
# File 'lib/configru.rb', line 43

def self.reload
  loaded_files = []
  @files.each do |file|
    if File.file?(file) && !File.zero?(file)
      self.load_file(file)
      loaded_files << file
    end
  end

  # Load all defaults if no files were loaded
  # TODO: loaded_files as instance var?
  # TODO: Better way to load defaults?
  @option_path = []
  self.load_group(@options, @root, {}) if loaded_files.empty?
end