Skip to content
Open
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
15 changes: 15 additions & 0 deletions lib/json-api-vanilla/parser.rb
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,8 @@ def self.parse(json)
# @param hash [Hash] parsed JSON API payload.
# @return [JSON::Api::Vanilla::Document] a wrapper for the objects.
def self.build(hash)
hash = normalize_hash(hash)

naive_validate(hash)
# Object storage.
container = Module.new
Expand Down Expand Up @@ -212,6 +214,19 @@ def self.naive_validate_relationship_object(hash)
end
end

def self.normalize_hash(object)
case object
when Hash
object.each_with_object({}) do |(key, value), result|
result[key.to_s] = normalize_hash(value)
end
when Array
object.map { |e| normalize_hash(e) }
else
object
end
end

class Document
# @return [Object, Array<Object>] the content of the JSON API data.
attr_reader :data
Expand Down
74 changes: 74 additions & 0 deletions spec/json-api-vanilla/diff_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -171,4 +171,78 @@ class TestClasses
expect(subject.name).to eql(data['attributes']['name'])
end
end

describe '.build(hash)' do
context 'with stringified keys' do
let(:hash) {
{
'data' => [
{
'id' => 'a123',
'type' => 'user',
'attributes' => {
'activated_at' => '2020-06-11'
}
}
]
}
}
subject { described_class.build(hash) }

it 'ceates a Document with data' do
expect(subject.data).to be_a(Array)
expect(subject.data[0].id).to eql(hash['data'][0]['id'])
expect(subject.data[0].type).to eql(hash['data'][0]['type'])
expect(subject.data[0].activated_at).to eql(hash['data'][0]['attributes']['activated_at'])
end
end

context 'with symbolized in keys' do
let(:hash) {
{
data: [
{
id: 'a123',
type: 'user',
attributes: {
activated_at: '2020-06-11'
}
}
]
}
}
subject { described_class.build(hash) }

it 'ceates a Document with data' do
expect(subject.data).to be_a(Array)
expect(subject.data[0].id).to eql(hash[:data][0][:id])
expect(subject.data[0].type).to eql(hash[:data][0][:type])
expect(subject.data[0].activated_at).to eql(hash[:data][0][:attributes][:activated_at])
end
end

end

describe '.normalize_hash' do
let(:hash) {
{
'data' => [
{
id: 1,
type: 'user',
'attributes' => {
'activated_at' => '2020-06-11'
}
}
]
}
}

subject { described_class.normalize_hash(hash) }

it 'returns hash with stringified keys' do
expect(subject['data'][0]['id']).to eql(hash['data'][0][:id])
expect(subject['data'][0]['type']).to eql(hash['data'][0][:type])
end
end
end