0

representerフラットな JSON で次の作業を行っています。

# 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

現在、 JSONAPI 1.0の仕様を実装していますが、次の json を解析できるリピーターを実装する方法がわかりません。

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

ヒントや提案を事前にありがとう

アップデート:

実用的なソリューションを含むGist

4

1 に答える 1

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)

データ配列を反復処理して、SongRepresenter プロパティにアクセスできるようになりました。

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">] 

hash または 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"}}]} 

そのため、AlbumRepresenter.new(OpenStruct.new).from_hash(hash) を使用しても、キーが記号化されているため機能しません。

于 2016-06-14T18:36:59.787 に答える