diff --git a/.ruby-version b/.ruby-version index acf9bf0..1454f6e 100644 --- a/.ruby-version +++ b/.ruby-version @@ -1 +1 @@ -3.2.2 \ No newline at end of file +4.0.1 diff --git a/lib/dvla/atlas/artefacts.rb b/lib/dvla/atlas/artefacts.rb index 4721b04..81422d8 100644 --- a/lib/dvla/atlas/artefacts.rb +++ b/lib/dvla/atlas/artefacts.rb @@ -19,6 +19,19 @@ def define_fields(*vargs, **kwargs) end end + sig { params(_options: T.untyped).returns(T::Hash[String, T.untyped]) } + def as_json(_options = nil) + instance_variables.each_with_object({}) do |var, hash| + name = var.to_s.delete_prefix('@') + value = send(:"#{name}") + + next if value.nil? + next if name.end_with?('_history') && value.empty? + + hash[name] = value + end + end + private sig { params(name: T.any(String, Symbol)).void } diff --git a/lib/dvla/atlas/version.rb b/lib/dvla/atlas/version.rb index 2de81ab..b1b314a 100644 --- a/lib/dvla/atlas/version.rb +++ b/lib/dvla/atlas/version.rb @@ -1,5 +1,5 @@ module DVLA module Atlas - VERSION = '1.1.0'.freeze + VERSION = '1.1.1'.freeze end end diff --git a/spec/dvla/atlas/artefacts_spec.rb b/spec/dvla/atlas/artefacts_spec.rb index e2f9d6c..9aa5c03 100644 --- a/spec/dvla/atlas/artefacts_spec.rb +++ b/spec/dvla/atlas/artefacts_spec.rb @@ -121,4 +121,25 @@ expect(artefacts.first_expected_method_history).to eq(%w[abc]) expect(artefacts.second_expected_method_history).to eq([123]) end + + describe '#as_json' do + it 'excludes fields that are nil' do + artefacts.define_fields('unset_field', set_field: 'value') + expect(artefacts.as_json).to eq({ 'set_field' => 'value' }) + end + + it 'excludes history fields for fields that have never been changed' do + artefacts.define_fields(username: 'initial') + json = artefacts.as_json + expect(json).to eq({ 'username' => 'initial' }) + expect(json).not_to have_key('username_history') + end + + it 'includes history fields for fields that have been changed' do + artefacts.define_fields(username: 'initial') + artefacts.username = 'updated' + json = artefacts.as_json + expect(json).to eq({ 'username' => 'updated', 'username_history' => ['initial'] }) + end + end end