Method: Grape::Entity.represent

Defined in:
lib/grape_entity/entity.rb

.represent(objects, options = {}) ⇒ Object

This convenience method allows you to instantiate one or more entities by passing either a singular or collection of objects. Each object will be initialized with the same options. If an array of objects is passed in, an array of entities will be returned. If a single object is passed in, a single entity will be returned.

Parameters:

  • objects (Object or Array)

    One or more objects to be represented.

  • options (Hash) (defaults to: {})

    Options that will be passed through to each entity representation.

Options Hash (options):

  • :root (String or false)

    override the default root name set for the entity. Pass nil or false to represent the object or objects with no root name even if one is defined for the entity.

  • :serializable (true or false)

    when true a serializable Hash will be returned

  • :only (Array)

    all the fields that should be returned

  • :except (Array)

    all the fields that should not be returned



438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
# File 'lib/grape_entity/entity.rb', line 438

def self.represent(objects, options = {})
  @present_collection ||= nil
  if objects.respond_to?(:to_ary) && !@present_collection
    root_element = root_element(:collection_root)
    inner = objects.to_ary.map { |object| new(object, options.reverse_merge(collection: true)).presented }
  else
    objects = { @collection_name => objects } if @present_collection
    root_element = root_element(:root)
    inner = new(objects, options).presented
  end

  root_element = options[:root] if options.key?(:root)

  root_element ? { root_element => inner } : inner
end