Rails 4: 使用可表示的解析 JSONAPI gem

Rails 4: Parsing JSONAPI using representable gem

我有以下工作 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 包含工作解决方案

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

请注意使用散列或 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) 不起作用,因为符号化键。