2016-06-14 14 views
0

mit habe ich die folgenden Arbeits representer für flache JSON arbeiten:Rails 4: Parsing JSONAPI darstellbare gem

# song_representer_spec.rb 
require 'rails_helper' 
require "representable/json" 
require "representable/json/collection" 

class Song < OpenStruct 
end 

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 

RSpec.describe "SongRepresenter" do 

    it "does work like charm" do 
    songs = SongRepresenter.new([]).from_json(simple_json) 
    expect(songs.first.title).to eq("Linoleum") 
    end 

    def simple_json 
    [{ 
     id: 1, 
     attributes: { 
     title: "Linoleum" 
     } 
     }].to_json 
    end 
end 

Wir werden jetzt die Spezifikationen von JSONAPI 1.0 Implementierung und ich kann nicht herausfinden, wie man einen Representer der Lage zu implementieren zu analysieren die folgende json:

{ 
    "data": [ 
    "type": "song", 
    "id": "1", 
    "attributes":{ 
     "title": "Linoleum" 
    } 
    ] 
} 

Danke im Voraus für Hinweise und Anregungen

Update:

Gist enthält eine Arbeitslösung

Antwort

1
require 'representable/json' 



class SongRepresenter < OpenStruct 
    include Representable::JSON 

    property :id 
    property :type 
    nested :attributes do 
    property :title 
    end 


end 


class AlbumRepresenter < Representable::Decorator 
    include Representable::JSON 

    collection :data, class: SongRepresenter 


end 


hash = { 
    "test": 1, 
    "data": [ 
    "type": "song", 
     "id": "1", 
     "attributes":{ 
      "title": "Linoleum" 
     } 
    ] 
} 

decorator = AlbumRepresenter.new(OpenStruct.new).from_json(hash.to_json) 

Sie können nun Ihre Daten-Array und den Zugang zu SongRepresenter Eigenschaften iterieren:

2.2.1 :046 > decorator = AlbumRepresenter.new(OpenStruct.new).from_json(hash.to_json) 
=> #<OpenStruct data=[#<SongRepresenter id="1", type="song", title="Linoleum">]> 
2.2.1 :047 > decorator.data 
=> [#<SongRepresenter id="1", type="song", title="Linoleum">] 

Bitte beachten Sie den Unterschied mit Hash oder JSON.parse (hash.to_json)

2.2.1 :049 > JSON.parse(hash.to_json) 
=> {"test"=>1, "data"=>[{"type"=>"song", "id"=>"1", "attributes"=>{"title"=>"Linoleum"}}]} 
2.2.1 :050 > hash 
=> {:test=>1, :data=>[{:type=>"song", :id=>"1", :attributes=>{:title=>"Linoleum"}}]} 

Also, mit AlbumRepresenter.new (OpenStruct.new) .from_hash (Hash) funktioniert nicht, weil symbolisierte Schlüssel.

+0

Vielen Dank für Ihre Hinweise! Es ist mir schließlich gelungen, einen 'Repräsentanten' zu erstellen, der ein OpenStruct zurückgibt, das alle meine Song-Klassenobjekte enthält. https://gist.github.com/mberlanda/e418808bbfa4d7258a95afae4dffa115 – mabe02