Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
json_api representer
require 'image/persistence'
class Image
class Representer < Roar::Decorator
include Roar::JSON::JSONAPI.resource :images
# top-level link.
link :self, toplevel: true do
"//images"
end
attributes do
property :caption
property :file_url
end
# resource object links
link(:self) { "http://images/#{represented.id}" }
end
end
require 'site/persistence'
class Site
class Representer < Roar::Decorator
include Roar::JSON::JSONAPI.resource :sites
# top-level link.
link :self, toplevel: true do
"//sites"
end
attributes do
property :name
property :reference
end
# resource object links
link(:self) { "http://sites/#{represented.id}" }
# relationships
has_one :feature_image, decorator: ::Image::Representer, class: ::Image::Persistence
has_many :images, decorator: ::Image::Representer, class: ::Image::Persistence
has_many :documents, decorator: ::Document::Representer, class: ::Document::Persistence
has_many :applications, decorator: ::FacultyApplication::BaseRepresenter, class: ::FacultyApplication::Persistence
end
end
# extract
# index - doesn't add include block to output when include option passed to_json
r.get do
sites = Site::Persistence.eager(:images).all
representer = Site::Representer.for_collection.new(sites)
response.write(representer.to_json(include: r.params["include"])
response.finish
end
# show - works fine when include option passed to_json
r.get do
site = ::Site::Persistence[id]
representer = Site::Representer.new(site)
response.write(representer.to_json(include: r.params["include"])
response.finish
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment