Skip to content

Instantly share code, notes, and snippets.

@mberlanda
Last active June 15, 2016 15:38
Show Gist options
  • Save mberlanda/e418808bbfa4d7258a95afae4dffa115 to your computer and use it in GitHub Desktop.
Save mberlanda/e418808bbfa4d7258a95afae4dffa115 to your computer and use it in GitHub Desktop.
Parsing JSONAPI using representable gem in Ruby on Rails 4
require 'rails_helper'
require 'representable/json'
require 'representable/json/collection'
class Song < OpenStruct
end
# Ex. 1 using standalone collections
class SongRepresenter < Representable::Decorator
include Representable::JSON
include Representable::JSON::Collection
items class: Song do
property :id
nested :attributes do
property :title
end
end
end
# Ex. 2 create a module for decorate one element of the object
module SongRepresenter2
include Representable::JSON
property :id
property :type
nested :attributes do
property :title
end
end
class AlbumRepresenter < Representable::Decorator
include Representable::JSON
collection :data, decorator: SongRepresenter2, class: Song
end
# Ex. 3 another approach using collection
class SimpleSongRepresenter < Representable::Decorator
include Representable::JSON
collection :data, class: Song do
property :id
property :type
nested :attributes do
property :title
end
end
end
RSpec.describe "SongRepresenter" do
it "ex.1 it works for simple_json" do
songs = SongRepresenter.new([]).from_json(simple_json)
expect(songs.first.title).to eq("Linoleum")
end
it "ex.2 album representer for jsonapi_sample" do
songs = AlbumRepresenter.new(OpenStruct.new).from_json(jsonapi_sample)
expect(songs.data.first.class).to eq(Song)
expect(songs.data.first.id).to eq(1)
expect(songs.data.first.title).to eq("Linoleum")
end
it "ex.3 simple song representer for jsonapi_sample" do
songs = SimpleSongRepresenter.new(OpenStruct.new).from_json(jsonapi_sample)
expect(songs.data.first.class).to eq(Song)
expect(songs.data.first.id).to eq(1)
expect(songs.data.first.title).to eq("Linoleum")
end
def simple_json
[{
id: 1,
attributes: {
title: "Linoleum"
}
}].to_json
end
def jsonapi_sample
{
data: [
id: 1,
attributes: {
title: "Linoleum"
}
]
}.to_json
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment