Module: Mixlib::Config

Defined in:
lib/mixlib/config.rb,
lib/mixlib/config/version.rb,
lib/mixlib/config/configurable.rb,
lib/mixlib/config/unknown_config_option_error.rb,
lib/mixlib/config/reopened_config_context_with_configurable_error.rb,
lib/mixlib/config/reopened_configurable_with_config_context_error.rb

Defined Under Namespace

Classes: Configurable, ReopenedConfigContextWithConfigurableError, ReopenedConfigurableWithConfigContextError, UnknownConfigOptionError

Constant Summary collapse

NOT_PASSED =
Object.new
VERSION =
"2.2.5"

Class Method Summary collapse

Instance Method Summary collapse

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(method_symbol, *args) ⇒ Object

Allows for simple lookups and setting of config options via method calls on Mixlib::Config. If there any arguments to the method, they are used to set the value of the config option. Otherwise, it’s a simple get operation.

Parameters

method_symbol<Symbol>

The method called. Must match a config option.

*args

Any arguments passed to the method

Returns

value

The value of the config option.

Raises

<UnknownConfigOptionError>

If the config option does not exist and strict mode is on.



547
548
549
550
# File 'lib/mixlib/config.rb', line 547

def method_missing(method_symbol, *args)
  method_symbol = $1.to_sym if method_symbol.to_s =~ /(.+)=$/
  internal_get_or_set(method_symbol, *args)
end

Class Method Details

.extended(base) ⇒ Object



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

def self.extended(base)
  class << base; attr_accessor :configuration; end
  class << base; attr_accessor :configurables; end
  class << base; attr_accessor :config_contexts; end
  class << base; attr_accessor :config_context_lists; end
  class << base; attr_accessor :config_context_hashes; end
  class << base; attr_accessor :config_parent; end
  base.configuration = Hash.new
  base.configurables = Hash.new
  base.config_contexts = Hash.new
  base.config_context_lists = Hash.new
  base.config_context_hashes = Hash.new
  base.initialize_mixlib_config
end

Instance Method Details

#[](config_option) ⇒ Object

Get the value of a config option

Parameters

config_option<Symbol>

The config option to return

Returns

value

The value of the config option

Raises

<UnknownConfigOptionError>

If the config option does not exist and strict mode is on.



121
122
123
# File 'lib/mixlib/config.rb', line 121

def [](config_option)
  internal_get(config_option.to_sym)
end

#[]=(config_option, value) ⇒ Object

Set the value of a config option

Parameters

config_option<Symbol>

The config option to set (within the [])

value

The value for the config option

Returns

value

The new value of the config option

Raises

<UnknownConfigOptionError>

If the config option does not exist and strict mode is on.



136
137
138
# File 'lib/mixlib/config.rb', line 136

def []=(config_option, value)
  internal_set(config_option.to_sym, value)
end

#config_attr_writer(method_symbol, &block) ⇒ Object

metaprogramming to ensure that the slot for method_symbol gets set to value after any other logic is run

Parameters

method_symbol<Symbol>

Name of the method (variable setter)

blk<Block>

logic block to run in setting slot method_symbol to value

value<Object>

Value to be set in config hash



325
326
327
# File 'lib/mixlib/config.rb', line 325

def config_attr_writer(method_symbol, &block)
  configurable(method_symbol).writes_value(&block)
end

#config_context(symbol, &block) ⇒ Object

Allows you to create a new config context where you can define new options with default values.

This method allows you to open up the configurable more than once.

For example:

config_context :server_info do

configurable(:url).defaults_to("http://localhost")

end

Parameters

symbol<Symbol>: the name of the context block<Block>: a block that will be run in the context of this new config class.



393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
# File 'lib/mixlib/config.rb', line 393

def config_context(symbol, &block)
  if configurables.has_key?(symbol)
    raise ReopenedConfigurableWithConfigContextError, "Cannot redefine config value #{symbol} with a config context"
  end

  if config_contexts.has_key?(symbol)
    context = config_contexts[symbol]
  else
    context = Class.new
    context.extend(::Mixlib::Config)
    context.config_parent = self
    config_contexts[symbol] = context
    define_attr_accessor_methods(symbol)
  end

  if block
    context.instance_eval(&block)
  end

  context
end

#config_context_hash(plural_symbol, singular_symbol, &block) ⇒ Object

Allows you to create a new hash of config contexts where you can define new options with default values.

This method allows you to open up the configurable more than once.

For example:

config_context_hash :listeners, :listener do

configurable(:url).defaults_to("http://localhost")

end

Parameters

symbol<Symbol>: the plural name for contexts in the list symbol<Symbol>: the singular name for contexts in the list block<Block>: a block that will be run in the context of this new config class.



463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
# File 'lib/mixlib/config.rb', line 463

def config_context_hash(plural_symbol, singular_symbol, &block)
  if configurables.has_key?(symbol)
    raise ReopenedConfigurableWithConfigContextError, "Cannot redefine config value #{plural_symbol} with a config context"
  end

  unless config_context_hashes.has_key?(plural_symbol)
    config_context_hashes[plural_symbol] = {
      definition_blocks: [],
      values: {},
    }
    define_hash_attr_accessor_methods(plural_symbol, singular_symbol)
  end

  config_context_hashes[plural_symbol][:definition_blocks] << block if block_given?
end

#config_context_list(plural_symbol, singular_symbol, &block) ⇒ Object

Allows you to create a new list of config contexts where you can define new options with default values.

This method allows you to open up the configurable more than once.

For example:

config_context_list :listeners, :listener do

configurable(:url).defaults_to("http://localhost")

end

Parameters

symbol<Symbol>: the plural name for contexts in the list symbol<Symbol>: the singular name for contexts in the list block<Block>: a block that will be run in the context of this new config class.



431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
# File 'lib/mixlib/config.rb', line 431

def config_context_list(plural_symbol, singular_symbol, &block)
  if configurables.has_key?(symbol)
    raise ReopenedConfigurableWithConfigContextError, "Cannot redefine config value #{plural_symbol} with a config context"
  end

  unless config_context_lists.has_key?(plural_symbol)
    config_context_lists[plural_symbol] = {
      definition_blocks: [],
      values: [],
    }
    define_list_attr_accessor_methods(plural_symbol, singular_symbol)
  end

  config_context_lists[plural_symbol][:definition_blocks] << block if block_given?
end

#config_strict_mode(value = NOT_PASSED) ⇒ Object

Gets or sets strict mode. When strict mode is on, only values which were specified with configurable(), default() or writes_with() may be retrieved or set. Getting or setting anything else will cause Mixlib::Config::UnknownConfigOptionError to be thrown.

If this is set to :warn, unknown values may be get or set, but a warning will be printed with Chef::Log.warn if this occurs.

Parameters

value<String>

pass this value to set strict mode [optional]

Returns

Current value of config_strict_mode

Raises

<ArgumentError>

if value is set to something other than true, false, or :warn



498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
# File 'lib/mixlib/config.rb', line 498

def config_strict_mode(value = NOT_PASSED)
  if value == NOT_PASSED
    if @config_strict_mode.nil?
      if config_parent
        config_parent.config_strict_mode
      else
        false
      end
    else
      @config_strict_mode
    end
  else
    self.config_strict_mode = value
  end
end

#config_strict_mode=(value) ⇒ Object

Sets strict mode. When strict mode is on, only values which were specified with configurable(), default() or writes_with() may be retrieved or set. All other values

If this is set to :warn, unknown values may be get or set, but a warning will be printed with Chef::Log.warn if this occurs.

Parameters

value<String>

pass this value to set strict mode [optional]

Raises

<ArgumentError>

if value is set to something other than true, false, or :warn



527
528
529
530
531
532
# File 'lib/mixlib/config.rb', line 527

def config_strict_mode=(value)
  if ![ true, false, :warn, nil ].include?(value)
    raise ArgumentError, "config_strict_mode must be true, false, nil or :warn"
  end
  @config_strict_mode = value
end

#configurable(symbol, &block) ⇒ Object

metaprogramming to set information about a config option. This may be used in one of two ways:

  1. Block-based:

configurable(:attr) do

defaults_to 4
writes_value { |value| 10 }

end

  1. Chain-based:

configurable(:attr).defaults_to(4).writes_value { |value| 10 }

Currently supported configuration:

defaults_to(value): value returned when configurable has no explicit value defaults_to BLOCK: block is run when the configurable has no explicit value writes_value BLOCK: block that is run to filter a value when it is being set

Parameters

symbol<Symbol>

Name of the config option

default_value<Object>

Default value [optional]

block<Block>

Logic block that calculates default value [optional]

Returns

The value of the config option.



364
365
366
367
368
369
370
371
372
373
374
375
376
# File 'lib/mixlib/config.rb', line 364

def configurable(symbol, &block)
  unless configurables[symbol]
    if config_contexts.has_key?(symbol)
      raise ReopenedConfigContextWithConfigurableError, "Cannot redefine config_context #{symbol} as a configurable value"
    end
    configurables[symbol] = Configurable.new(symbol)
    define_attr_accessor_methods(symbol)
  end
  if block
    yield(configurables[symbol])
  end
  configurables[symbol]
end

#configure {|configuration| ... } ⇒ Object

Pass Mixlib::Config.configure() a block, and it will yield itself

Parameters

block<Block>

A block that is called with self.configuration as the argument.

Yields:

  • (configuration)


107
108
109
# File 'lib/mixlib/config.rb', line 107

def configure(&block)
  yield(configuration)
end

#default(symbol, default_value = nil, &block) ⇒ Object

metaprogramming to set the default value for the given config option

Parameters

symbol<Symbol>

Name of the config option

default_value<Object>

Default value (can be unspecified)

block<Block>

Logic block that calculates default value



335
336
337
# File 'lib/mixlib/config.rb', line 335

def default(symbol, default_value = nil, &block)
  configurable(symbol).defaults_to(default_value, &block)
end

#delete(symbol) ⇒ Object

Resets a config option to its default.

Parameters

symbol<Symbol>

Name of the config option



156
157
158
# File 'lib/mixlib/config.rb', line 156

def delete(symbol)
  configuration.delete(symbol)
end

#from_file(filename) ⇒ Object

Loads a given ruby file, and runs instance_eval against it in the context of the current object.

Raises an IOError if the file cannot be found, or is not readable.

Parameters

filename<String>

A filename to read from



55
56
57
58
59
60
61
62
63
# File 'lib/mixlib/config.rb', line 55

def from_file(filename)
  if %w{ .yml .yaml }.include?(File.extname(filename))
    from_yaml(filename)
  elsif File.extname(filename) == ".json"
    from_json(filename)
  else
    instance_eval(IO.read(filename), filename, 1)
  end
end

#from_hash(hash, filename = "in_memory") ⇒ Object

Transforms a Hash into method-style configuration syntax to be processed

Parameters

hash<Hash>

A Hash containing configuration



87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
# File 'lib/mixlib/config.rb', line 87

def from_hash(hash, filename = "in_memory")
  ruby_translation = []

  to_dotted_hash(hash).each do |k, v|
    if v.is_a? Array
      ruby_translation << "#{k} #{v}"
    elsif v.is_a? String
      ruby_translation << "#{k} \"#{v}\""
    else
      ruby_translation << "#{k} #{v}"
    end
  end

  instance_eval(ruby_translation.join("\n"), filename, 1)
end

#from_json(filename) ⇒ Object

Parses valid JSON structure into Ruby

Parameters

filename<String>

A filename to read from



78
79
80
81
# File 'lib/mixlib/config.rb', line 78

def from_json(filename)
  require "json"
  from_hash(JSON.parse(IO.read(filename)), filename)
end

#from_yaml(filename) ⇒ Object

Parses valid YAML structure into Ruby so it can be ingested into the Class

Parameters

filename<String>

A filename to read from



69
70
71
72
# File 'lib/mixlib/config.rb', line 69

def from_yaml(filename)
  require "yaml"
  from_hash(YAML.load(IO.read(filename)), filename)
end

#has_key?(key) ⇒ Boolean

Check if Mixlib::Config has a config option.

Parameters

key<Symbol>

The config option to check for

Returns

<True>

If the config option exists

<False>

If the config option does not exist

Returns:

  • (Boolean)


148
149
150
# File 'lib/mixlib/config.rb', line 148

def has_key?(key)
  configuration.has_key?(key.to_sym)
end

#hash_dupObject

Creates a shallow copy of the internal hash NOTE: remove this in 3.0 in favor of save. This is completely useless with default values and configuration_context.

Returns

result of Hash#dup



313
314
315
# File 'lib/mixlib/config.rb', line 313

def hash_dup
  save
end

#initialize_mixlib_configObject



44
45
46
# File 'lib/mixlib/config.rb', line 44

def initialize_mixlib_config
  @config_strict_mode = nil
end

#keysObject

Return the set of config hash keys. This only returns hash keys which have been set by the user. In future versions this will likely be removed in favor of something more explicit. For now though, we want this to match has_key?

Returns

result of Hash#keys



303
304
305
# File 'lib/mixlib/config.rb', line 303

def keys
  configuration.keys
end

#merge!(hash) ⇒ Object

Merge an incoming hash with our config options

Parameters

hash<Hash>: a hash in the same format as output by save.

Returns

self



284
285
286
287
288
289
290
291
292
293
294
# File 'lib/mixlib/config.rb', line 284

def merge!(hash)
  hash.each do |key, value|
    if config_contexts.has_key?(key)
      # Grab the config context and let internal_get cache it if so desired
      config_contexts[key].restore(value)
    else
      configuration[key] = value
    end
  end
  self
end

#resetObject

Resets all config options to their defaults.



161
162
163
164
# File 'lib/mixlib/config.rb', line 161

def reset
  self.configuration = Hash.new
  config_contexts.values.each { |config_context| config_context.reset }
end

#restore(hash) ⇒ Object

Restore non-default values from the given hash.

Parameters

hash<Hash>: a hash in the same format as output by save.

Returns

self



246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
# File 'lib/mixlib/config.rb', line 246

def restore(hash)
  self.configuration = hash.reject { |key, value| config_contexts.has_key?(key) }
  config_contexts.each do |key, config_context|
    if hash.has_key?(key)
      config_context.restore(hash[key])
    else
      config_context.reset
    end
  end
  config_context_lists.each do |key, meta|
    meta[:values] = []
    if hash.has_key?(key)
      hash[key].each do |val|
        context = define_context(meta[:definition_blocks])
        context.restore(val)
        meta[:values] << context
      end
    end
  end
  config_context_hashes.each do |key, meta|
    meta[:values] = {}
    if hash.has_key?(key)
      hash[key].each do |vkey, val|
        context = define_context(meta[:definition_blocks])
        context.restore(val)
        meta[:values][vkey] = context
      end
    end
  end
end

#save(include_defaults = false) ⇒ Object Also known as: to_hash

Makes a copy of any non-default values.

This returns a shallow copy of the hash; while the hash itself is duplicated a la dup, modifying data inside arrays and hashes may modify the original Config object.

Returns

Hash of values the user has set.

Examples

For example, this config class:

class MyConfig < Mixlib::Config
  default :will_be_set, 1
  default :will_be_set_to_default, 1
  default :will_not_be_set, 1
  configurable(:computed_value) { |x| x*2 }
  config_context :group do
    default :will_not_be_set, 1
  end
  config_context :group_never_set
end

MyConfig.x = 2
MyConfig.will_be_set = 2
MyConfig.will_be_set_to_default = 1
MyConfig.computed_value = 2
MyConfig.group.x = 3

produces this:

MyConfig.save == {
  :x => 2,
  :will_be_set => 2,
  :will_be_set_to_default => 1,
  :computed_value => 4,
  :group => {
    :x => 3
  }
}


209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
# File 'lib/mixlib/config.rb', line 209

def save(include_defaults = false)
  result = configuration.dup
  if include_defaults
    (configurables.keys - result.keys).each do |missing_default|
      # Ask any configurables to save themselves into the result array
      if configurables[missing_default].has_default
        result[missing_default] = configurables[missing_default].default
      end
    end
  end
  config_contexts.each_pair do |key, context|
    context_result = context.save(include_defaults)
    result[key] = context_result if context_result.size != 0 || include_defaults
  end
  config_context_lists.each_pair do |key, meta|
    meta[:values].each do |context|
      context_result = context.save(include_defaults)
      result[key] = (result[key] || []) << context_result if context_result.size != 0 || include_defaults
    end
  end
  config_context_hashes.each_pair do |key, meta|
    meta[:values].each_pair do |context_key, context|
      context_result = context.save(include_defaults)
      (result[key] ||= {})[context_key] = context_result if context_result.size != 0 || include_defaults
    end
  end
  result
end