Created
March 15, 2014 00:58
-
-
Save nickls/9560205 to your computer and use it in GitHub Desktop.
POC: Grape entity bug - overwriting previous entities. issue #56
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
# Example config.ru | |
# See: https://github.com/intridea/grape-entity/issues/56 | |
require 'sinatra' | |
require 'grape' | |
require 'grape-entity' | |
class Media | |
attr_accessor :user, :id | |
def initialize(_id) | |
@id=_id | |
@user = User.new(_id + 8) | |
end | |
def anonymous | |
if @id > 90 | |
true | |
else | |
false | |
end | |
end | |
end | |
class User | |
attr_accessor :id | |
def initialize(_id) | |
@id=_id | |
end | |
def name | |
"Nick#{@id}" | |
end | |
end | |
class API < Grape::API | |
format :json | |
class UserEntity < Grape::Entity | |
expose :id | |
expose :name | |
end | |
class AnonymousUserEntity < Grape::Entity | |
expose :id | |
end | |
class BrokenMediaEntity < Grape::Entity | |
expose :id | |
expose :user, using: AnonymousUserEntity, if: lambda { |object, options| object.anonymous == true } | |
expose :user, using: UserEntity, if: lambda { |object, options| object.anonymous == false } | |
end | |
class MediaEntity < Grape::Entity | |
expose :id | |
expose :user, using: AnonymousUserEntity, if: lambda { |object, options| object.anonymous == true } | |
end | |
# Output from /broken (first user object is missing) | |
# [ | |
# { | |
# "id": 99 | |
# }, | |
# { | |
# "id": 10, | |
# "user": { | |
# "id": 18, | |
# "name": "Nick18" | |
# } | |
# } | |
# ] | |
# | |
# See expected output at bottom of the file. | |
get "broken" do | |
media = [Media.new(99), Media.new(10)] | |
present media, with: BrokenMediaEntity | |
end | |
# Output from /media (after removing the second expose) | |
# [ | |
# { | |
# "id": 99, | |
# "user": { | |
# "id": 107 | |
# } | |
# }, | |
# { | |
# "id": 10 | |
# } | |
# ] | |
get "media" do | |
media = [Media.new(99), Media.new(10)] | |
present media, with: MediaEntity | |
end | |
# expected output from /broken | |
# [ | |
# { | |
# "id": 99, | |
# "user": { | |
# "id": 107 | |
# } | |
# }, | |
# { | |
# "id": 10, | |
# "user": { | |
# "id": 18, | |
# "name": "Nick18" | |
# } | |
# } | |
# ] | |
end | |
use Rack::Session::Cookie | |
run Rack::Cascade.new [API] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment