Skip to content

Commit

Permalink
Attempt to call an objects as_json method in the normalizer if it has…
Browse files Browse the repository at this point in the history
… one.
  • Loading branch information
Jeff Utter committed May 14, 2016
1 parent e157f47 commit 839cb2c
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 0 deletions.
1 change: 1 addition & 0 deletions lib/hedgelog/normalizer.rb
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ def normalize_array(array)

def normalize_thing(thing)
return '' if thing.nil?
thing = thing.as_json if thing.respond_to?(:as_json)
return normalize_struct(thing) if thing.is_a?(Struct)
return normalize_array(thing) if thing.is_a?(Array)
return normalize_hash(thing) if thing.is_a?(Hash)
Expand Down
15 changes: 15 additions & 0 deletions spec/hedgelog/normalizer_spec.rb
Original file line number Diff line number Diff line change
@@ -1,12 +1,19 @@
require 'spec_helper'
require 'hedgelog/normalizer'

class CustomJSONObject
def as_json
'JSON'
end
end

describe Hedgelog::Normalizer do
subject(:instance) { described_class.new }
let(:struct_class) { Struct.new(:foo, :bar) }
let(:struct) { struct_class.new(1234, 'dummy') }
let(:hash) { {message: 'dummy=1234'} }
let(:array) { ['dummy string', {message: 'dummy=1234'}] }

describe '#normalize' do
it 'returns the normalized data' do
expect(instance.normalize(hash)).to include(message: 'dummy=1234')
Expand All @@ -20,24 +27,32 @@
instance.normalize(data)
expect(myvar).to eq orig_myvar
end

it 'uses an objects as_json method if available' do
expect(instance.normalize(foo: CustomJSONObject.new)).to include(foo: 'JSON')
end
end

describe '#normalize_hash' do
it 'returns a normalized hash' do
expect(instance.normalize_hash(hash)).to include(message: 'dummy=1234')
end
end

describe '#normalize_struct' do
it 'returns struct as a normalized hash' do
expect(instance.normalize_struct(struct)).to include(foo: 1234, bar: 'dummy')
end
end

describe '#normalize_array' do
it 'returns array as a json string' do
normalized_array = instance.normalize_array(array)
expect(normalized_array).to be_a String
expect(normalized_array).to eq '["dummy string",{"message":"dummy=1234"}]'
end
end

context 'When a hash contains different types of data' do
let(:data) { hash }
before :each do
Expand Down

0 comments on commit 839cb2c

Please sign in to comment.