Module: Chef::Mixin::ParamsValidate

Defined Under Namespace

Classes: SetOrReturnProperty

Instance Method Summary collapse

Instance Method Details

#lazy(&block) ⇒ Object



117
118
119
# File 'lib/chef/mixin/params_validate.rb', line 117

def lazy(&block)
  DelayedEvaluator.new(&block)
end

#set_or_return(symbol, value, validation) ⇒ Object



121
122
123
124
# File 'lib/chef/mixin/params_validate.rb', line 121

def set_or_return(symbol, value, validation)
  property = SetOrReturnProperty.new(name: symbol, **validation)
  property.call(self, value)
end

#validate(opts, map) ⇒ Object

Takes a hash of options, along with a map to validate them. Returns the original options hash, plus any changes that might have been made (through things like setting default values in the validation map)

For example:

validate({ :one => "neat" }, { :one => { :kind_of => String }})

Would raise an exception if the value of :one above is not a kind_of? string. Valid map options are:

Raises:

  • (ArgumentError)


83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
# File 'lib/chef/mixin/params_validate.rb', line 83

def validate(opts, map)
  map = map.validation_options if map.is_a?(Property)

  #--
  # validate works by taking the keys in the validation map, assuming it's a hash, and
  # looking for _pv_:symbol as methods.  Assuming it find them, it calls the right
  # one.
  #++
  raise ArgumentError, "Options must be a hash" unless opts.kind_of?(Hash)
  raise ArgumentError, "Validation Map must be a hash" unless map.kind_of?(Hash)

  map.each do |key, validation|
    unless key.kind_of?(Symbol) || key.kind_of?(String)
      raise ArgumentError, "Validation map keys must be symbols or strings!"
    end
    case validation
    when true
      _pv_required(opts, key)
    when false
      true
    when Hash
      validation.each do |check, carg|
        check_method = "_pv_#{check}"
        if respond_to?(check_method, true)
          send(check_method, opts, key, carg)
        else
          raise ArgumentError, "Validation map has unknown check: #{check}"
        end
      end
    end
  end
  opts
end