Method: Chef::Resource.build_from_file

Defined in:
lib/chef/resource.rb

.build_from_file(cookbook_name, filename) ⇒ Object



460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
# File 'lib/chef/resource.rb', line 460

def build_from_file(cookbook_name, filename)
  rname = filename_to_qualified_string(cookbook_name, filename)

  # Add log entry if we override an existing light-weight resource.
  class_name = convert_to_class_name(rname)
  overriding = Chef::Resource.const_defined?(class_name)
  Chef::Log.info("#{class_name} light-weight resource already initialized -- overriding!") if overriding
    
  new_resource_class = Class.new self do |cls|
    
    # default initialize method that ensures that when initialize is finally
    # wrapped (see below), super is called in the event that the resource
    # definer does not implement initialize
    def initialize(name, run_context)
      super(name, run_context)
    end
    
    @actions_to_create = []
    
    class << cls
      include Chef::Mixin::FromFile
      
      def actions_to_create
        @actions_to_create
      end
      
      define_method(:actions) do |*action_names|
        actions_to_create.push(*action_names)
      end
    end
    
    # load resource definition from file
    cls.class_from_file(filename)
    
    # create a new constructor that wraps the old one and adds the actions
    # specified in the DSL
    old_init = instance_method(:initialize)

    define_method(:initialize) do |name, *optional_args|
      args_run_context = optional_args.shift
      @resource_name = rname.to_sym
      old_init.bind(self).call(name, args_run_context)
      allowed_actions.push(self.class.actions_to_create).flatten!
    end
  end
  
  # register new class as a Chef::Resource
  class_name = convert_to_class_name(rname)
  Chef::Resource.const_set(class_name, new_resource_class)
  Chef::Log.debug("Loaded contents of #{filename} into a resource named #{rname} defined in Chef::Resource::#{class_name}")
  
  new_resource_class
end