Skip to content

Instantly share code, notes, and snippets.

@mach-kernel
Created March 3, 2017 04:55
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 mach-kernel/dc417914d80153585d58e75fd89e99f6 to your computer and use it in GitHub Desktop.
Save mach-kernel/dc417914d80153585d58e75fd89e99f6 to your computer and use it in GitHub Desktop.
# frozen_string_literal: true
# ez auto entities
# dstancu@nyu.edu
module API
module Entities
class Collection < Grape::Roar::Decorator
include Roar::JSON
include Roar::Hypermedia
class << self
def represent(object, _options = {})
extract_from_relation(object) if object.is_a?(ActiveRecord::Relation)
super
end
private
def extract_from_relation(relation)
str_klass = relation.klass.name.demodulize
collection(str_klass.downcase.pluralize.to_sym,
extend: "API::Entities::#{str_klass}".constantize,
class: relation.klass)
relation.class.send(
:define_method,
str_klass.downcase.pluralize,
-> { self }
)
end
end
link :self do |opts|
request = Grape::Request.new(opts[:env])
"#{request.base_url}#{request.path}/#{represented.try(:id)}"
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment