Class: Chef::Property

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

Overview

Type and validation information for a property on a resource.

A property named "x" manipulates the "@x" instance variable on a resource. The presence of the variable (instance_variable_defined?(@x)) tells whether the variable is defined; it may have any actual value, constrained only by validation.

Properties may have validation, defaults, and coercion, and have full support for lazy values.

See Also:

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(**options) ⇒ Property

Create a new property.

Parameters:

  • options (Hash<Symbol,Object>)

    Property options, including control options here, as well as validation options (see Chef::Mixin::ParamsValidate#validate for a description of validation options). @option options [Symbol] :name The name of this property. @option options [Class] :declared_in The class this property comes from. @option options [Symbol] :instance_variable_name The instance variable tied to this property. Must include a leading @. Defaults to @<name>. nil means the property is opaque and not tied to a specific instance variable. @option options [Boolean] :desired_state true if this property is part of desired state. Defaults to true. @option options [Boolean] :identity true if this property is part of object identity. Defaults to false. @option options [Boolean] :name_property true if this property defaults to the same value as name. Equivalent to default: lazy { name }, except that #property_is_set? will return true if the property is set or if name is set. @option options [Boolean] :nillable true opt-in to Chef-13 style behavior where attempting to set a nil value will really set a nil value instead of issuing a warning and operating like a getter [DEPRECATED] @option options [Object] :default The value this property will return if the user does not set one. If this is lazy, it will be run in the context of the instance (and able to access other properties) and cached. If not, the value will be frozen with Object#freeze to prevent users from modifying it in an instance. @option options [Proc] :coerce A proc which will be called to transform the user input to canonical form. The value is passed in, and the transformed value returned as output. Lazy values will not be passed to this method until after they are evaluated. Called in the context of the resource (meaning you can access other properties). @option options [Boolean] :required true if this property must be present; false otherwise. This is checked after the resource is fully initialized.


92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
# File 'lib/chef/property.rb', line 92

def initialize(**options)
  options = options.inject({}) { |memo, (key, value)| memo[key.to_sym] = value; memo }
  @options = options
  options[:name] = options[:name].to_sym if options[:name]
  options[:instance_variable_name] = options[:instance_variable_name].to_sym if options[:instance_variable_name]

  # Replace name_attribute with name_property
  if options.has_key?(:name_attribute)
    # If we have both name_attribute and name_property and they differ, raise an error
    if options.has_key?(:name_property)
      raise ArgumentError, "Cannot specify both name_property and name_attribute together on property #{self}."
    end
    # replace name_property with name_attribute in place
    options = Hash[options.map { |k, v| k == :name_attribute ? [ :name_property, v ] : [ k, v ] }]
    @options = options
  end

  if options.has_key?(:default) && options.has_key?(:name_property)
    raise ArgumentError, "Cannot specify both default and name_property/name_attribute together on property #{self}"
  end

  # Recursively freeze the default if it isn't a lazy value.
  unless default.is_a?(DelayedEvaluator)
    visitor = lambda do |obj|
      case obj
      when Hash
        obj.each_value { |value| visitor.call(value) }
      when Array
        obj.each { |value| visitor.call(value) }
      end
      obj.freeze
    end
    visitor.call(default)
  end

  # Validate the default early, so the user gets a good error message, and
  # cache it so we don't do it again if so
  begin
    # If we can validate it all the way to output, do it.
    @stored_default = input_to_stored_value(nil, default, is_default: true)
  rescue Chef::Exceptions::CannotValidateStaticallyError
    # If the validation is not static (i.e. has procs), we will have to
    # coerce and validate the default each time we run
  end
end

Instance Attribute Details

#optionsObject (readonly)

The options this Property will use for get/set behavior and validation.


539
540
541
# File 'lib/chef/property.rb', line 539

def options
  @options
end

Class Method Details

.derive(**options) ⇒ Object

Create a reusable property type that can be used in multiple properties in different resources.

Examples:

Property.derive(default: 'hi')

Parameters:

  • options (Hash<Symbol,Object>)

    Validation options. See Chef::Resource.property for the list of options.


50
51
52
# File 'lib/chef/property.rb', line 50

def self.derive(**options)
  new(**options)
end

Instance Method Details

#call(resource, value = NOT_PASSED) ⇒ Object

Handle the property being called.

The base implementation does the property get-or-set:

resource.myprop # get
resource.myprop value # set

Subclasses may implement this with any arguments they want, as long as the corresponding DSL calls it correctly.

Parameters:

  • resource (Chef::Resource)

    The resource to get the property from.

  • value (defaults to: NOT_PASSED)

    The value to set (or NOT_PASSED if it is a get).

Returns:

  • The current value of the property. If it is a set, lazy values will be returned without running, validating or coercing. If it is a get, the non-lazy, coerced, validated value will always be returned.


279
280
281
282
283
284
285
# File 'lib/chef/property.rb', line 279

def call(resource, value = NOT_PASSED)
  if value == NOT_PASSED
    get(resource)
  else
    set(resource, value)
  end
end

#coerce(resource, value) ⇒ Object

Coerce an input value into canonical form for the property.

After coercion, the value is suitable for storage in the resource. You must validate values after coercion, however.

Does no special handling for lazy values.

Parameters:

  • resource (Chef::Resource)

    The resource we're coercing against (to provide context for the coerce).

  • value

    The value to coerce.

Returns:

  • The coerced value.

Raises:

  • Chef::Exceptions::ValidationFailed If the value is invalid for this property.


443
444
445
446
447
448
449
450
451
# File 'lib/chef/property.rb', line 443

def coerce(resource, value)
  if options.has_key?(:coerce)
    # nil is never coerced
    unless value.nil?
      value = exec_in_resource(resource, options[:coerce], value)
    end
  end
  value
end

#declared_inClass

The class this property was defined in.

Returns:

  • (Class)

156
157
158
# File 'lib/chef/property.rb', line 156

def declared_in
  options[:declared_in]
end

#defaultObject

The raw default value for this resource.

Does not coerce or validate the default. Does not evaluate lazy values.

Defaults to lazy { name } if name_property is true; otherwise defaults to nil


183
184
185
186
187
# File 'lib/chef/property.rb', line 183

def default
  return options[:default] if options.has_key?(:default)
  return Chef::DelayedEvaluator.new { name } if name_property?
  nil
end

#derive(**modified_options) ⇒ Property

Derive a new Property that is just like this one, except with some added or changed options.

Parameters:

  • options (Hash<Symbol,Object>)

    List of options that would be passed to #initialize.

Returns:


487
488
489
490
491
492
493
494
495
496
497
498
# File 'lib/chef/property.rb', line 487

def derive(**modified_options)
  # Since name_property, name_attribute and default override each other,
  # if you specify one of them in modified_options it overrides anything in
  # the original options.
  options = self.options
  if modified_options.has_key?(:name_property) ||
      modified_options.has_key?(:name_attribute) ||
      modified_options.has_key?(:default)
    options = options.reject { |k, v| k == :name_attribute || k == :name_property || k == :default }
  end
  self.class.new(options.merge(modified_options))
end

#desired_state?Boolean

Whether this is part of desired state or not.

Defaults to true.

Returns:

  • (Boolean)

205
206
207
208
# File 'lib/chef/property.rb', line 205

def desired_state?
  return true if !options.has_key?(:desired_state)
  options[:desired_state]
end

#emit_dslObject

Emit the DSL for this property into the resource class (declared_in).

Creates a getter and setter for the property.


505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
# File 'lib/chef/property.rb', line 505

def emit_dsl
  # We don't create the getter/setter if it's a custom property; we will
  # be using the existing getter/setter to manipulate it instead.
  return if !instance_variable_name

  # Properties may override existing properties up the inheritance heirarchy, but
  # properties must not override inherited methods like Object#hash.  When the Resource is
  # placed into the resource collection the ruby Hash object will call the
  # Object#hash method on the resource, and overriding that with a property will cause
  # very confusing results.
  if property_redefines_method?
    resource_name = declared_in.respond_to?(:resource_name) ? declared_in.resource_name : declared_in
    raise ArgumentError, "Property `#{name}` of resource `#{resource_name}` overwrites an existing method."
  end

  # We prefer this form because the property name won't show up in the
  # stack trace if you use `define_method`.
  declared_in.class_eval <<-EOM, __FILE__, __LINE__ + 1
    def #{name}(value=NOT_PASSED)
      raise "Property `#{name}` of `\#{self}` was incorrectly passed a block.  Possible property-resource collision.  To call a resource named `#{name}` either rename the property or else use `declare_resource(:#{name}, ...)`" if block_given?
      self.class.properties[#{name.inspect}].call(self, value)
    end
    def #{name}=(value)
      raise "Property `#{name}` of `\#{self}` was incorrectly passed a block.  Possible property-resource collision.  To call a resource named `#{name}` either rename the property or else use `declare_resource(:#{name}, ...)`" if block_given?
      self.class.properties[#{name.inspect}].set(self, value)
    end
  EOM
end

#explicitly_accepts_nil?(resource) ⇒ Boolean

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Find out whether this type accepts nil explicitly.

A type accepts nil explicitly if "is" allows nil, it validates as nil, and is not simply an empty type.

A type is presumed to accept nil if it does coercion (which must handle nil).

These examples accept nil explicitly:

property :a, [ String, nil ]
property :a, [ String, NilClass ]
property :a, [ String, proc { |v| v.nil? } ]

This does not (because the "is" doesn't exist or doesn't have nil):

property :x, String

These do not, even though nil would validate fine (because they do not have "is"):

property :a
property :a, equal_to: [ 1, 2, 3, nil ]
property :a, kind_of: [ String, NilClass ]
property :a, respond_to: [ ]
property :a, callbacks: { "a" => proc { |v| v.nil? } }

Parameters:

  • resource (Chef::Resource)

    The resource we're coercing against (to provide context for the coerce).

Returns:

  • (Boolean)

    Whether this value explicitly accepts nil.


579
580
581
582
# File 'lib/chef/property.rb', line 579

def explicitly_accepts_nil?(resource)
  options.has_key?(:coerce) ||
    (options.has_key?(:is) && resource.send(:_pv_is, { name => nil }, name, options[:is], raise_error: false))
end

#get(resource, nil_set: false) ⇒ Object

Get the property value from the resource, handling lazy values, defaults, and validation.

  • If the property's value is lazy, it is evaluated, coerced and validated.
  • If the property has no value, and is required, raises ValidationFailed.
  • If the property has no value, but has a lazy default, it is evaluated, coerced and validated. If the evaluated value is frozen, the resulting
  • If the property has no value, but has a default, the default value will be returned and frozen. If the default value is lazy, it will be evaluated, coerced and validated, and the result stored in the property.
  • If the property has no value, but is name_property, resource.name is retrieved, coerced, validated and stored in the property.
  • Otherwise, nil is returned.

Parameters:

  • resource (Chef::Resource)

    The resource to get the property from.

Returns:

  • The value of the property.

Raises:

  • Chef::Exceptions::ValidationFailed If the value is invalid for this property, or if the value is required and not set.


309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
# File 'lib/chef/property.rb', line 309

def get(resource, nil_set: false)
  # If it's set, return it (and evaluate any lazy values)
  value = nil

  if is_set?(resource)
    value = get_value(resource)
    value = stored_value_to_output(resource, value)
  else
    # We are getting the default value.

    # If the user does something like this:
    #
    # ```
    # class MyResource < Chef::Resource
    #   property :content
    #   action :create do
    #     file '/x.txt' do
    #       content content
    #     end
    #   end
    # end
    # ```
    #
    # It won't do what they expect. This checks whether you try to *read*
    # `content` while we are compiling the resource.
    if !nil_set &&
        resource.respond_to?(:resource_initializing) &&
        resource.resource_initializing &&
        resource.respond_to?(:enclosing_provider) &&
        resource.enclosing_provider &&
        resource.enclosing_provider.new_resource &&
        resource.enclosing_provider.new_resource.respond_to?(name)
      Chef::Log.warn("#{Chef::Log.caller_location}: property #{name} is declared in both #{resource} and #{resource.enclosing_provider}. Use new_resource.#{name} instead. At #{Chef::Log.caller_location}")
    end

    if has_default?
      # If we were able to cache the stored_default, grab it.
      if defined?(@stored_default)
        value = @stored_default
      else
        # Otherwise, we have to validate it now.
        value = input_to_stored_value(resource, default, is_default: true)
      end
      value = stored_value_to_output(resource, value, is_default: true)

      # If the value is mutable (non-frozen), we set it on the instance
      # so that people can mutate it.  (All constant default values are
      # frozen.)
      if !value.frozen? && !value.nil?
        set_value(resource, value)
      end
    end
  end

  if value.nil? && required?
    raise Chef::Exceptions::ValidationFailed, "#{name} is required"
  else
    value
  end
end

#get_value(resource) ⇒ Object

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.


585
586
587
588
589
590
591
# File 'lib/chef/property.rb', line 585

def get_value(resource)
  if instance_variable_name
    resource.instance_variable_get(instance_variable_name)
  else
    resource.send(name)
  end
end

#has_default?Boolean

Whether this property has a default value.

Returns:

  • (Boolean)

224
225
226
# File 'lib/chef/property.rb', line 224

def has_default?
  options.has_key?(:default) || name_property?
end

#identity?Boolean

Whether this is part of the resource's natural identity or not.

Returns:

  • (Boolean)

194
195
196
# File 'lib/chef/property.rb', line 194

def identity?
  options[:identity]
end

#instance_variable_nameSymbol

The instance variable associated with this property.

Defaults to @<name>

Returns:


167
168
169
170
171
172
173
# File 'lib/chef/property.rb', line 167

def instance_variable_name
  if options.has_key?(:instance_variable_name)
    options[:instance_variable_name]
  elsif name
    :"@#{name}"
  end
end

#is_set?(resource) ⇒ Boolean

Find out whether this property has been set.

This will be true if:

  • The user explicitly set the value
  • The property has a default, and the value was retrieved.

From this point of view, it is worth looking at this as "what does the user think this value should be." In order words, if the user grabbed the value, even if it was a default, they probably based calculations on it. If they based calculations on it and the value changes, the rest of the world gets inconsistent.

Parameters:

  • resource (Chef::Resource)

    The resource to get the property from.

Returns:

  • (Boolean)

412
413
414
# File 'lib/chef/property.rb', line 412

def is_set?(resource)
  value_is_set?(resource)
end

#nameString

The name of this property.

Returns:


147
148
149
# File 'lib/chef/property.rb', line 147

def name
  options[:name]
end

#name_property?Boolean

Whether this is name_property or not.

Returns:

  • (Boolean)

215
216
217
# File 'lib/chef/property.rb', line 215

def name_property?
  options[:name_property]
end

#required?Boolean

Whether this property is required or not.

Returns:

  • (Boolean)

233
234
235
# File 'lib/chef/property.rb', line 233

def required?
  options[:required]
end

#reset(resource) ⇒ Object

Reset the value of this property so that is_set? will return false and the default will be returned in the future.

Parameters:

  • resource (Chef::Resource)

    The resource to get the property from.


422
423
424
# File 'lib/chef/property.rb', line 422

def reset(resource)
  reset_value(resource)
end

#reset_value(resource) ⇒ Object

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.


612
613
614
615
616
617
618
619
620
# File 'lib/chef/property.rb', line 612

def reset_value(resource)
  if instance_variable_name
    if value_is_set?(resource)
      resource.remove_instance_variable(instance_variable_name)
    end
  else
    raise ArgumentError, "Property #{name} has no instance variable defined and cannot be reset"
  end
end

#sensitive?Boolean

Whether this property is sensitive or not.

Defaults to false.

Returns:

  • (Boolean)

244
245
246
# File 'lib/chef/property.rb', line 244

def sensitive?
  options.fetch(:sensitive, false)
end

#set(resource, value) ⇒ Object

Set the value of this property in the given resource.

Non-lazy values are coerced and validated before being set. Coercion and validation of lazy values is delayed until they are first retrieved.

Parameters:

  • resource (Chef::Resource)

    The resource to set this property in.

  • value

    The value to set.

Returns:

  • The value that was set, after coercion (if lazy, still returns the lazy value)

Raises:

  • Chef::Exceptions::ValidationFailed If the value is invalid for this property.


385
386
387
388
389
390
391
392
393
# File 'lib/chef/property.rb', line 385

def set(resource, value)
  value = set_value(resource, input_to_stored_value(resource, value))

  if value.nil? && required?
    raise Chef::Exceptions::ValidationFailed, "#{name} is required"
  else
    value
  end
end

#set_value(resource, value) ⇒ Object

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.


594
595
596
597
598
599
600
# File 'lib/chef/property.rb', line 594

def set_value(resource, value)
  if instance_variable_name
    resource.instance_variable_set(instance_variable_name, value)
  else
    resource.send(name, value)
  end
end

#to_sObject


138
139
140
# File 'lib/chef/property.rb', line 138

def to_s
  "#{name || "<property type>"}#{declared_in ? " of resource #{declared_in.resource_name}" : ""}"
end

#validate(resource, value) ⇒ Object

Validate a value.

Calls Chef::Mixin::ParamsValidate#validate with #validation_options as options.

Parameters:

  • resource (Chef::Resource)

    The resource we're validating against (to provide context for the validate).

  • value

    The value to validate.

Raises:

  • Chef::Exceptions::ValidationFailed If the value is invalid for this property.


466
467
468
469
470
471
472
473
474
475
476
# File 'lib/chef/property.rb', line 466

def validate(resource, value)
  # nils are not validated unless we have an explicit default value
  if !value.nil? || has_default?
    if resource
      resource.validate({ name => value }, { name => validation_options })
    else
      name = self.name || :property_type
      Chef::Mixin::ParamsValidate.validate({ name => value }, { name => validation_options })
    end
  end
end

#validation_optionsHash<Symbol,Object>

Validation options. (See Chef::Mixin::ParamsValidate#validate.)

Returns:


253
254
255
256
257
# File 'lib/chef/property.rb', line 253

def validation_options
  @validation_options ||= options.reject do |k, v|
    [:declared_in, :name, :instance_variable_name, :desired_state, :identity, :default, :name_property, :coerce, :required, :nillable, :sensitive].include?(k)
  end
end

#value_is_set?(resource) ⇒ Boolean

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Returns:

  • (Boolean)

603
604
605
606
607
608
609
# File 'lib/chef/property.rb', line 603

def value_is_set?(resource)
  if instance_variable_name
    resource.instance_variable_defined?(instance_variable_name)
  else
    true
  end
end