diff --git a/lib/puppet/resource_api/glue.rb b/lib/puppet/resource_api/glue.rb index 85628c3e..d0a2371a 100644 --- a/lib/puppet/resource_api/glue.rb +++ b/lib/puppet/resource_api/glue.rb @@ -41,6 +41,13 @@ def to_hierayaml YAML.dump('type' => { title => attributes }).split("\n").drop(2).join("\n") + "\n" end + def to_json(*) + attrs = filtered_keys.map { |k| [k.to_s, values[k]] unless values[k].nil? } + attributes = Hash[*attrs.compact.flatten] + resource = { title => attributes } + resource.to_json + end + # attribute names that are not title or namevars def filtered_keys values.keys.reject { |k| k == :title || !attr_def[k] || (attr_def[k][:behaviour] == :namevar && @namevars.size == 1) } diff --git a/spec/integration/resource_api_spec.rb b/spec/integration/resource_api_spec.rb index c4ff82ba..b8d1cdf8 100644 --- a/spec/integration/resource_api_spec.rb +++ b/spec/integration/resource_api_spec.rb @@ -223,6 +223,10 @@ def get(_context) describe 'its title' do it { expect(instance.to_resource.title).to eq 'somename' } end + + it 'can serialize to json' do + expect({ 'resources' => [instance.to_resource] }.to_json).to eq '{"resources":[{"somename":{"ensure":"absent","boolean_param":false,"integer_param":99,"float_param":3.21,"ensure_param":"present","variant_pattern_param":"1234ABCD","url_param":"http://www.puppet.com","string_array_param":"d","e":"f","string_param":"default value"}}]}' # rubocop:disable Metrics/LineLength + end end it('ensure is reported as a symbol') { expect(instance[:ensure]).to be_a Symbol } diff --git a/spec/puppet/resource_api/glue_spec.rb b/spec/puppet/resource_api/glue_spec.rb index 2a1ee68d..dabc79f3 100644 --- a/spec/puppet/resource_api/glue_spec.rb +++ b/spec/puppet/resource_api/glue_spec.rb @@ -47,6 +47,23 @@ end end + describe '.to_json' do + it { expect(instance.to_json).to eq '{"title":{"attr":"value","attr_ro":"fixed"}}' } + + context 'with nil values' do + subject(:instance) do + described_class.new({ namevarname: title, attr: nil, attr_ro: 'fixed' }, 'typename', [:namevarname], + namevarname: { type: 'String', behaviour: :namevar, desc: 'the title' }, + attr: { type: 'String', desc: 'a string parameter' }, + attr_ro: { type: 'String', desc: 'a string readonly', behaviour: :read_only }) + end + + it 'doesn\'t output them' do + expect(instance.to_json).to eq '{"title":{"attr_ro":"fixed"}}' + end + end + end + describe '.to_hierayaml' do it { expect(instance.to_hierayaml).to eq " title:\n attr: value\n attr_ro: fixed\n" }