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.
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) = args.count > 1 ? args. : {} key, object = if args.count == 2 && args.first.is_a?(Symbol) args else [nil, args.first] end entity_class = .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 = .delete(:root) representation = if entity_class = { env: env } [:version] = env['api.version'] if env['api.version'] entity_class.represent(object, .merge()) else object end representation = { root => representation } if root representation = (@body || {}).merge(key => representation) if key body representation end |