Skip to content

Instantly share code, notes, and snippets.

@ordoghl
Created September 19, 2013 14:02
Show Gist options
  • Save ordoghl/6623954 to your computer and use it in GitHub Desktop.
Save ordoghl/6623954 to your computer and use it in GitHub Desktop.
Polymorphic association in a grape entity
require_relative 'customer.rb'
require_relative 'contact.rb'
require_relative 'agent.rb'
module Api
module V1
module Entities
class Ticket < Grape::Entity
expose :id
expose :subject
expose :description
expose :customer, using: Api::V1::Entities::Customer
expose :contact, using: Api::V1::Entities::Contact
expose :created_by do |ticket, options|
if ticket.created_by.class.to_s == 'Contact'
{ "contact" => Api::V1::Entities::Contact.represent(ticket.created_by) }
else
{ "agent" => Api::V1::Entities::Agent.represent(ticket.created_by) }
end
end
expose :created_at
expose :updated_at
end
end
end
end
@hcarreras
Copy link

This is working, unfortunately I couldn't make it work in a dynamic way:

expose :created_by do |ticket, options|
   { ticket.class.to_s.underscore => send("Api::V1::Entities::#{ticket.class.singularize.constantize}.represent", ticket.created_by) }
end

It returns undefined method represent fir class Contact. Not pretty sure why.

@pinkynrg
Copy link

pinkynrg commented Oct 11, 2017

@hcarreras something like the following is working for me:

expose :content do |panel|
  Api::V1::Entities::const_get(panel.content_type).represent(panel.content)
end

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment