-
Notifications
You must be signed in to change notification settings - Fork 153
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Expose collection of items of different types without keys #137
Comments
Oh yeah, and the response I'm getting is:
|
It will be possible to achieve this when #56 will be fixed. I made an attempt here: #151. require 'grape_entity'
require 'date'
require 'json'
Post = Struct.new(:id, :title, :date) do
def type
'posts'
end
end
User = Struct.new(:id, :first_name, :last_name) do
def type
'users'
end
end
class PostAttributes < Grape::Entity
expose :title
expose :date
end
class UserAttributes < Grape::Entity
expose :first_name
expose :last_name
end
class ResultEntity < Grape::Entity
class Included < Grape::Entity
expose :id
expose :type
expose :attributes,
using: PostAttributes,
if: ->(obj, opts) { obj.is_a? Post },
proc: ->(obj, opts) { obj }
expose :attributes,
using: UserAttributes,
if: ->(obj, opts) { obj.is_a? User },
proc: ->(obj, opts) { obj }
end
def included
object[:posts] + [object[:user]]
end
expose :included, using: Included
end
model = {
posts: [
Post.new(11, 'post #1', Date.parse('2015-01-01')),
Post.new(12, 'post #2', Date.parse('2015-02-01'))
],
user: User.new(1, 'Vladimir', 'Kochnev')
}
puts JSON.pretty_generate ResultEntity.represent(model, serializable: true) Output:
Main caveat of this approach: as more included entities will be added, more |
Also it looks like you're trying to implement JSON API compliant entities. |
Thanks for the heads up. And yes, I was trying to implement JSON API v1.0, though unsuccessfully with Grape::Entity, so I switched over to Roar. Another problem is that Grape Swagger does not really support deeply nested models/parameters, but that's another story. |
I have been using Roar in production as well, and cannot encourage everyone to stick to a Hypermedia standard enough. So, I would welcome Grape::Entity support for HAL and JSON API as well. |
Hey guys, I was also trying to implement a JSON API using grape / grape-entity / grape-sagger. |
Hi.
I've recently tried to expose collection of objects of different types, but it seems that it's not possible with a current version.
Here's the result I'm trying to achieve:
And classes:
Is there something I am missing?
The text was updated successfully, but these errors were encountered: