Module: Grape::DSL::Entity
- Included in:
- InsideRoute
- Defined in:
- lib/grape/dsl/entity.rb
Instance Method Summary collapse
-
#entity_class_for_obj(object) ⇒ Class
Attempt to locate the Entity class for a given object, if not given explicitly.
-
#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
:withoption.
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.
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.
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, **) 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, ) : 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 |