lib/mixlib/config/configurable.rb in mixlib-config-2.2.11 vs lib/mixlib/config/configurable.rb in mixlib-config-2.2.12
- old
+ new
@@ -1,8 +1,8 @@
#
# Author:: John Keiser (<jkeiser@chef.io>)
-# Copyright:: Copyright (c) 2013-2016 Chef Software, Inc.
+# Copyright:: Copyright (c) 2013-2018, Chef Software Inc.
# License:: Apache License, Version 2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
@@ -17,57 +17,74 @@
#
module Mixlib
module Config
class Configurable
+ attr_reader :symbol
+ attr_reader :default_value
+ attr_reader :default_block
+
def initialize(symbol)
@symbol = symbol
- @default_block = nil
- @has_default = false
- @default_value = nil
- @writes_value = nil
end
- attr_reader :has_default
+ def has_default?
+ instance_variable_defined?(:@default_value)
+ end
+ def writes_value?
+ instance_variable_defined?(:@writes_value)
+ end
+
+ def default_block?
+ instance_variable_defined?(:@default_block)
+ end
+
+ alias_method :has_default, :has_default?
+
def defaults_to(default_value = nil, &block)
- @has_default = true
- @default_block = block
@default_value = default_value
+ @default_block = block if block_given?
self
end
def writes_value(&block)
@writes_value = block
self
end
def get(config)
- if config.has_key?(@symbol)
- config[@symbol]
- elsif @default_block
- @default_block.call
+ if config.key?(symbol)
+ config[symbol]
+ elsif default_block?
+ default_block.call
else
- begin
- # Some things cannot be dup'd, and you won't know this till after the fact
- # because all values implement dup
- config[@symbol] = @default_value.dup
- rescue TypeError
- @default_value
- end
+ config[symbol] = safe_dup(default_value)
end
end
def set(config, value)
- config[@symbol] = @writes_value ? @writes_value.call(value) : value
+ config[symbol] = writes_value? ? @writes_value.call(value) : value
end
def default
- if @default_block
- @default_block.call
+ if default_block?
+ default_block.call
else
- @default_value
+ default_value
end
+ end
+
+ def is_default?(config)
+ !config.key?(symbol) || config[symbol] == default_value
+ end
+
+ private
+
+ def safe_dup(e)
+ e.dup
+ rescue TypeError
+ e
end
end
end
end