grape-entity
grape-entity copied to clipboard
:only/:except options for expose
These options are useful to specify exposed fields for a using entity per request:
class User < GE
expose :name
expose :email
expose :age
end
class Responce1 < GE
expose :users, using: User, only: :name
end
class Respose2 < GE
expose :users, using: User, except: :email
end
class Respose3 < GE
expose :users, using: User, except: :name
end
As the result we have one shared type (User) that can be used in different context that need only specific fields from that type.
Isn't this feature essentially already available? https://github.com/ruby-grape/grape-entity#returning-only-the-fields-you-want
@dchandekstark I don't think so. The reference you pointed is about evaluating (or data processing) step. But this PR is about types definition and use it with inheritance.
Actually, this PR is not essential. On the project we've come up with the following base class:
# Example:
#
# module Map
# class UsersLocationsResponseSerializer < ApplicationSerializer
# # Array of Hashes with Symbol keys that's response of Queries::Map::LastLocations
# expose :locations, using: LocationSerializer
# # Array of Hashes with Symbol keys that's response of Queries::Map::LastActivities
# expose_nested :activities do
# expose :user_id
# expose_time :last_client_activity
# end
# # Array of Task
# expose :tasks, using: TaskSerializer, only: %i[id summary]
# # Array of User
# expose :users, using: UserSerializer, except: %i[email]
# # Boolean, true means the map should be fully redrawn (significant changes since last request)
# expose :clear
# end
# end
class ApplicationSerializer < Grape::Entity
# Extends the standard functionality with `:only` and `:except` options that
# define exact serializable fields for the nested structures specified with `:using`.
#
# @note The `:only` and `:except` options can be used only along with `:using`.
# @see Grape::Entity.expose for the standard set of attributes.
def self.expose(*attributes, only: nil, except: nil, **options)
if only || except
using_class = options.delete(:using)
raise ArgumentError, ':only or :except options can be used only with :using' unless using_class
expose(*attributes, **options, format_with: proc { using_class.represent(_1, only: only, except: except) })
else
super(*attributes, **options)
end
end
# Defines _in-line_ serializers.
def self.expose_nested(attribute, **options, &block)
entity_class = Class.new(ApplicationSerializer, &block)
const_set("#{name.demodulize}_#{attribute}", entity_class)
expose(attribute, using: entity_class, **options, &block)
end
end