intridea/grape — Issue #95: presenting overwrites the response body
Author: lucasefe
Created: 2011-12-06 15:11:01+00:00
State: open

Hello,

I want to be able to provide json responses with a prefix, like this:

{ thing: { name: "The Name" } }

But if I do:

{ thing: present(thing, using: ThingEntity) }

I get { name: "The Name" } instead of the expected response.

The method present overwrite the response body, so my action returned value is omitted.

I could add a method named (for example) *represent* to do the same thing *present* is doing but not overwriting body, and let *present* call *represent*. Let the code speak for itself.

def represent(object, options = {})
entity_class = options.delete(:with)

object.class.ancestors.each do |potential|
entity_class ||= self.class.options[:representations][potential]
end

if entity_class
embeds = {:env => env}
embeds[:version] = env['api.version'] if env['api.version']
entity_class.represent(object, embeds.merge(options))
end

end

def present(object, options = {})
body represent(object, options)
end

Of course, this may be unnecessary, and someone can point me in the right direction.

BTW, the purpose of returning the hash is to be able to return more than the object. Think about adding messages, or other context information, or go-to urls.

{
thing: represent(thing),
url: '/api/v1/....',
more: '/api/v1/thing/1/more'
}

Thanks in advance.

Lucas