Method: Grape::Endpoint#present

Defined in:
lib/grape/endpoint.rb

#present(*args) ⇒ Object

Allows you to make use of Grape Entities by setting the response body to the serializable hash of the entity provided in the :with option. This has the added benefit of automatically passing along environment and version information to the serialization, making it very easy to do conditional exposures. See Entity docs for more info.

Examples:


get '/users/:id' do
  present User.find(params[:id]),
    with: API::Entities::User,
    admin: current_user.admin?
end


318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
# File 'lib/grape/endpoint.rb', line 318

def present(*args)
  options = args.count > 1 ? args.extract_options! : {}
  key, object = if args.count == 2 && args.first.is_a?(Symbol)
                  args
                else
                  [nil, args.first]
                end
  entity_class = options.delete(:with)

  # auto-detect the entity from the first object in the collection
  object_instance = object.respond_to?(:first) ? object.first : object

  object_instance.class.ancestors.each do |potential|
    entity_class ||= (settings[:representations] || {})[potential]
  end

  entity_class ||= object_instance.class.const_get(:Entity) if object_instance.class.const_defined?(:Entity)

  root = options.delete(:root)

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

  representation = { root => representation } if root
  representation = (@body || {}).merge(key => representation) if key
  body representation
end