Module: Chef::DSL::DeclareResource

Included in:
Recipe, Provider::AptUpdate
Defined in:
lib/chef/dsl/declare_resource.rb

Instance Method Summary collapse

Instance Method Details

#build_resource(type, name, created_at = nil, run_context: self.run_context, &resource_attrs_block) ⇒ Chef::Resource

Instantiate a resource of the given type with the given name and attributes as given in the resource_attrs_block.

The resource is NOT added to the resource collection.

Examples:

build_resource(:file, '/x/y.txy', caller[0]) do
  action :delete
end


89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
# File 'lib/chef/dsl/declare_resource.rb', line 89

def build_resource(type, name, created_at = nil, run_context: self.run_context, &resource_attrs_block)
  created_at ||= caller[0]
  Thread.exclusive do
    require "chef/resource_builder" unless defined?(Chef::ResourceBuilder)
  end

  Chef::ResourceBuilder.new(
    type:                type,
    name:                name,
    created_at:          created_at,
    params:              @params,
    run_context:         run_context,
    cookbook_name:       cookbook_name,
    recipe_name:         recipe_name,
    enclosing_provider:  self.is_a?(Chef::Provider) ? self : nil
  ).build(&resource_attrs_block)
end

#declare_resource(type, name, created_at = nil, run_context: self.run_context, create_if_missing: false, &resource_attrs_block) ⇒ Chef::Resource

Instantiates a resource (via #build_resource), then adds it to the resource collection. Note that resource classes are looked up directly, so this will create the resource you intended even if the method name corresponding to that resource has been overridden.

Examples:

declare_resource(:file, '/x/y.txy', caller[0]) do
  action :delete
end
# Equivalent to
file '/x/y.txt' do
  action :delete
end


51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
# File 'lib/chef/dsl/declare_resource.rb', line 51

def declare_resource(type, name, created_at = nil, run_context: self.run_context, create_if_missing: false, &resource_attrs_block)
  created_at ||= caller[0]

  if create_if_missing
    begin
      resource = run_context.resource_collection.find(type => name)
      return resource
    rescue Chef::Exceptions::ResourceNotFound
    end
  end

  resource = build_resource(type, name, created_at, &resource_attrs_block)

  run_context.resource_collection.insert(resource, resource_type: type, instance_name: name)
  resource
end