From ac3894819967aa731e8a7d26b44582706bcb2967 Mon Sep 17 00:00:00 2001 From: Ben Ford Date: Mon, 9 May 2016 13:41:20 -0700 Subject: [PATCH] This allows you to manage symbol keys Given a hash like ```puppet $symbols = { ":bar" => { "baz" => "foo", "moo" => 1, ":cow" => "1", } } ``` Prior to this commit, this type would manage a hash with literal keys with the colon in them and it was impossible to manage a hash with symbolic keys. This commit will convert a string like `":thing"` to a symbol, like `:thing` when managing yaml files. Fixes #2 --- examples/json.pp | 27 +++++++++++++++++++++++++++ examples/yaml.pp | 27 +++++++++++++++++++++++++++ lib/puppet/type/hash_file.rb | 21 +++++++++++++++++++++ 3 files changed, 75 insertions(+) create mode 100644 examples/json.pp create mode 100644 examples/yaml.pp diff --git a/examples/json.pp b/examples/json.pp new file mode 100644 index 0000000..d489dc0 --- /dev/null +++ b/examples/json.pp @@ -0,0 +1,27 @@ +$data = { + "bar" => { + "baz" => "foo", + "moo" => 1, + "cow" => "1", + } +} + + +$symbols = { + ":bar" => { + "baz" => "foo", + "moo" => 1, + ":cow" => "1", + } +} + + +hash_file { '/tmp/hash.json': + value => $data, + provider => 'json', +} + +hash_file { '/tmp/symbols.json': + value => $symbols, + provider => 'json', +} diff --git a/examples/yaml.pp b/examples/yaml.pp new file mode 100644 index 0000000..da04e0a --- /dev/null +++ b/examples/yaml.pp @@ -0,0 +1,27 @@ +$data = { + "bar" => { + "baz" => "foo", + "moo" => 1, + "cow" => "1", + } +} + + +$symbols = { + ":bar" => { + "baz" => "foo", + "moo" => 1, + ":cow" => "1", + } +} + + +hash_file { '/tmp/hash.yaml': + value => $data, + provider => 'yaml', +} + +hash_file { '/tmp/symbols.yaml': + value => $symbols, + provider => 'yaml', +} diff --git a/lib/puppet/type/hash_file.rb b/lib/puppet/type/hash_file.rb index 840efb7..1624df0 100644 --- a/lib/puppet/type/hash_file.rb +++ b/lib/puppet/type/hash_file.rb @@ -16,6 +16,27 @@ raise ArgumentError, "Value is not of type Hash" end end + + # convert strings like ":thing" to a symbolic representation, :thing + # This is needed to manage symbol keys in yaml files. + munge do |value| + return value unless resource[:provider] == :yaml + resource.symbolize_keys(value) + end + end + + def symbolize_keys(data) + data.each_with_object({}) do |item, memo| + key, val = item + + val = symbolize_keys(val) if val.class == Hash + + if key =~ /^:/ + memo[key[1..-1].to_sym] = val + else + memo[key] = val + end + end end end