Skip to content

Instantly share code, notes, and snippets.

@agent462
Created February 5, 2013 15:15
Show Gist options
  • Save agent462/4715041 to your computer and use it in GitHub Desktop.
Save agent462/4715041 to your computer and use it in GitHub Desktop.
class Chef::Provider::JsonFile < Chef::Provider::File
def load_json(path)
JSON.parse(::File.read(path)) rescue Hash.new
end
def dump_json(obj)
JSON.pretty_generate(obj) + "\n"
end
def to_mash(obj)
Mash.from_hash(obj)
end
def compare_content
to_mash(load_json(@current_resource.path)) == to_mash(@new_resource.content)
end
def set_content
unless compare_content
backup @new_resource.path if ::File.exists?(@new_resource.path)
::File.open(@new_resource.path, "w") { |file| file.write dump_json(@new_resource.content) }
Chef::Log.info("#{@new_resource} updated file #{@new_resource.path}")
@new_resource.updated_by_last_action(true)
end
end
def action_create
# chef >= 10.14.0
if respond_to?(:define_resource_requirements)
define_resource_requirements
else
assert_enclosing_directory_exists!
end
set_content
# chef >= 0.10.10
if respond_to?(:enforce_ownership_and_permissions)
updated = @new_resource.updated_by_last_action?
enforce_ownership_and_permissions
@new_resource.updated_by_last_action(true) if updated
else
set_owner unless @new_resource.owner.nil?
set_group unless @new_resource.group.nil?
set_mode unless @new_resource.mode.nil?
end
end
end
class Chef::Resource::JsonFile < Chef::Resource::File
def self.attribute(attr_name, validation_opts={})
# Ruby 1.8 doesn't support default arguments to blocks, but we have to
# use define_method with a block to capture +validation_opts+.
# Workaround this by defining two methods :(
class_eval(<<-SHIM, __FILE__, __LINE__)
def #{attr_name}(arg=nil)
_set_or_return_#{attr_name}(arg)
end
SHIM
define_method("_set_or_return_#{attr_name.to_s}".to_sym) do |arg|
set_or_return(attr_name.to_sym, arg, validation_opts)
end
end
attribute :content, :kind_of => Hash
def initialize(name, run_context=nil)
super
@resource_name = :json_file
@provider = Chef::Provider::JsonFile
end
end
@skymob
Copy link

skymob commented Feb 6, 2013

Working for me, thanks! 👍

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment