Module: Grape::DSL::Entity

Included in:
InsideRoute
Defined in:
lib/grape/dsl/entity.rb

Instance Method Summary collapse

Instance Method Details

#entity_class_for_obj(object) ⇒ Class

Attempt to locate the Entity class for a given object, if not given explicitly. This is done by looking for the presence of Klass::Entity, where Klass is the class of the ‘object` parameter, or one of its ancestors.

Parameters:

  • object (Object)

    the object to locate the Entity class for

Returns:

  • (Class)

    the located Entity class, or nil if none is found



51
52
53
54
55
56
57
58
59
60
61
62
63
64
# File 'lib/grape/dsl/entity.rb', line 51

def entity_class_for_obj(object)
  klass = object_class(object)

  representations = inheritable_setting.namespace_stackable_with_hash(:representations)
  if representations
    potential = klass.ancestors.detect { |potential| representations.key?(potential) }
    return representations[potential] if potential && representations[potential]
  end

  return unless klass.const_defined?(:Entity)

  entity = klass.const_get(:Entity)
  entity if entity.respond_to?(:represent)
end

#present(*args, root: nil, with: nil, **options) ⇒ 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

Parameters:

  • args (Array)

    either ‘(object)` or `(key, object)` where key is a Symbol used to nest the representation under that key in the response body.

  • root (Symbol, String, nil) (defaults to: nil)

    wraps the representation under this root key.

  • with (Class, nil) (defaults to: nil)

    the entity class to use for representation. If omitted, the entity class is inferred from the object via #entity_class_for_obj.

  • options (Hash)

    additional options forwarded to the entity’s ‘represent` call.



28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# File 'lib/grape/dsl/entity.rb', line 28

def present(*args, root: nil, with: nil, **options)
  key, object = args.count == 2 && args.first.is_a?(Symbol) ? args : [nil, args.first]
  entity_class = with || entity_class_for_obj(object)
  representation = entity_class ? entity_representation_for(entity_class, object, options) : object
  representation = { root => representation } if root

  if key
    representation = body&.merge(key => representation) || { key => representation }
  elsif entity_class.present? && body
    raise ArgumentError, "Representation of type #{representation.class} cannot be merged." unless representation.respond_to?(:merge)

    representation = body.merge(representation)
  end

  body representation
end