Skip to content

Instantly share code, notes, and snippets.

@fran-worley
Last active July 28, 2017 10:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fran-worley/39451042e02244d7efa9af3d9f952d58 to your computer and use it in GitHub Desktop.
Save fran-worley/39451042e02244d7efa9af3d9f952d58 to your computer and use it in GitHub Desktop.
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