double-z
12/6/2014 - 7:44 AM

chef-apply this and MAGIC

chef-apply this and MAGIC

module Chef::DSL::Recipe
  #
  # Sets defaults for a named resource
  #
  # defaults :file, :directory do
  #   owner 'jkeiser'
  #   group 'wheel'
  #   mode 0777
  # end
  #
  # After this, all "file" and "directory" resources will by default be owned by jkeiser, have group 'wheel', and have mode 0777.
  #
  def defaults(*resource_names, &defaults_block)
    resource_names.each do |resource_name|
      resource_alias(resource_name, resource_name, &defaults_block)
    end
  end

  #
  # Creates a new alias of a resource:
  # resource_alias :small_machine, :machine do
  #   machine_options { ... }
  # end
  #
  def resource_alias(new_resource_name, old_resource_name, &defaults_block)
    self.class.send(:define_method, new_resource_name) do |*args, &block|
      # Call method missing to invoke the underlying resource
      method_missing(old_resource_name, *args) do
        instance_eval(&defaults_block)
        instance_eval(&block)
      end
    end
  end
end


defaults :file do
  mode 0777
end
file '/Users/jkeiser/x.txt' do
  content 'hi there'
end

resource_alias :my_file, :file do
  mode 0770
end
my_file '/Users/jkeiser/y.txt' do
  content 'no no no'
end