Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

convert data values using to_json #23

Merged
merged 2 commits into from
Jun 28, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions lib/dfe/analytics/event.rb
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,8 @@ def with_request_uuid(request_id)

def hash_to_kv_pairs(hash)
hash.map do |(key, value)|
value = value.try(:as_json)

if value.in? [true, false]
value = value.to_s
elsif value.is_a?(Hash)
Expand Down
17 changes: 17 additions & 0 deletions spec/dfe/analytics/event_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,17 @@
end

describe 'data pairs' do
let(:has_as_json_class) do
Struct.new(:colour, :is_cat) do
def as_json
{
colour: colour,
is_cat: is_cat
}
end
end
end

it 'converts booleans to strings' do
event = described_class.new
output = event.with_data(key: true).as_json
Expand All @@ -73,6 +84,12 @@
output = event.with_data(key: { equality_and_diversity: { ethnic_background: 'Irish' } }).as_json
expect(output['data'].first['value']).to eq ['{"equality_and_diversity":{"ethnic_background":"Irish"}}']
end

it 'handles objects that have JSON-friendly structures' do
event = described_class.new
output = event.with_data(as_json_object: has_as_json_class.new(:green, true)).as_json
expect(output['data'].first['value']).to eq ['{"colour":"green","is_cat":true}']
end
end

def fake_request(overrides = {})
Expand Down
1 change: 1 addition & 0 deletions spec/spec_helper.rb
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

ENV['RAILS_ENV'] = 'test'
require_relative '../spec/dummy/config/environment'
require 'debug'
require 'rspec/rails'
require 'webmock/rspec'
require 'json-schema'
Expand Down