Method: Chef::Resource.use

Defined in:
lib/chef/resource.rb

.use(partial) ⇒ Object

Use a partial code fragment. This can be used for code sharing between multiple resources.

Do not wrap the code fragment in a class or module. It also does not support the use of super to subclass any methods defined in the fragment, the methods will just be overwritten.

Parameters:

  • partial (String)

    the code fragment to eval against the class



1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
# File 'lib/chef/resource.rb', line 1509

def self.use(partial)
  if partial =~ /^core::(.*)/
    partial = $1
    dirname = ::File.dirname(partial)
    basename = ::File.basename(partial, ".rb")
    basename = basename[1..] if basename.start_with?("_")
    class_eval IO.read(::File.expand_path("resource/#{dirname}/_#{basename}.rb", __dir__))
  else
    dirname = ::File.dirname(partial)
    basename = ::File.basename(partial, ".rb")
    basename = basename[1..] if basename.start_with?("_")

    # Support recursive `use`
    callers = caller_locations
    used_from = if callers.first.label == "use"
                  callers.detect { |caller| caller.label == "class_from_file" }.path
                else
                  callers.first.path
                end

    fullpath = ::File.expand_path("#{dirname}/_#{basename}.rb", ::File.dirname(used_from))
    class_eval IO.read(fullpath)
  end
end