Method: Grape::DSL::InsideRoute#entity_class_for_obj

Defined in:
lib/grape/dsl/inside_route.rb

#entity_class_for_obj(object, options) ⇒ 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

  • options (Hash)

Options Hash (options):

  • :with (Class)

    the explicit entity class to use

Returns:

  • (Class)

    the located Entity class, or nil if none is found



434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
# File 'lib/grape/dsl/inside_route.rb', line 434

def entity_class_for_obj(object, options)
  entity_class = options.delete(:with)

  if entity_class.nil?
    # entity class not explicitly defined, auto-detect from relation#klass or first object in the collection
    object_class = if object.respond_to?(:klass)
                     object.klass
                   else
                     object.respond_to?(:first) ? object.first.class : object.class
                   end

    object_class.ancestors.each do |potential|
      entity_class ||= (namespace_stackable_with_hash(:representations) || {})[potential]
    end

    entity_class ||= object_class.const_get(:Entity) if object_class.const_defined?(:Entity) && object_class.const_get(:Entity).respond_to?(:represent)
  end

  entity_class
end