Created
March 3, 2017 04:55
-
-
Save mach-kernel/dc417914d80153585d58e75fd89e99f6 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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