Skip to content

Commit

Permalink
handle data that have JSON-friendly representation
Browse files Browse the repository at this point in the history
When converting event data into the JSON payload to send to BQ, have
special handling for Hash objects. However, some data will come in as on
object that isn't immediately convertable to something JSON-friendly,
such as models (e.g. StoreModel or ActiveModel objects).

This change converts everything to a more standard JSON-friendly
representation before processing for sending to BQ, meaning that models
are converted to a Hash object which we can then to_json as needed.
  • Loading branch information
misaka committed Jun 28, 2022
1 parent 46c0947 commit dfd0e38
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 0 deletions.
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

0 comments on commit dfd0e38

Please sign in to comment.