An API focused facade that sits on top of an object model.
An API focused facade that sits on top of an object model.
This gem adds Entity support to API frameworks, such as Grape. Grape's Entity is an API focused facade that sits on top of an object model.
module API
module Entities
class Status 418, 'message' => "I'm a teapot" }).as_json
#=> { code: 418, message: "I'm a teapot" }Don't derive your model classes from Grape::Entity, expose them using a presenter.
expose :replies, using: API::Entities::Status, as: :responsesPresenter classes can also be specified in string format, which helps with circular dependencies.
expose :replies, using: "API::Entities::Status", as: :responsesUse :if or :unless to expose fields conditionally.
expose :ip, if: { type: :full }
expose :ip, if: lambda { |instance, options| options[:type] == :full } # exposed if the function evaluates to true
expose :ip, if: :type # exposed if :type is available in the options hash
expose :ip, if: { type: :full } # exposed if options :type has a value of :full
expose :ip, unless: ... # the opposite of :ifDon't raise an exception and expose as nil, even if the :x cannot be evaluated.
expose :ip, safe: trueSupply a block to define a hash using nested exposures.
expose :contact_info do
expose :phone
expose :address, using: API::Entities::Address
endYou can also conditionally expose attributes in nested exposures:
expose :contact_info do
expose :phone
expose :address, using: API::Entities::Address
expose :email, if: lambda { |instance, options| options[:type] == :full }
endUse root(plural, singular = nil) to expose an object or a collection of objects with a root key.
root 'users', 'user'
expose :id, :name, ...By default every object of a collection is wrapped into an instance of your Entity class.
You can override this behavior and wrap the whole collection into one instance of your Entity
class.
As example:
present_collection true, :collection_name # `collection_name` is optional and defaults to `items`
expose :collection_name, using: API::Entities::Items
Use :merge option to merge fields into the hash or into the root:
expose :contact_info do
expose :phone
expose :address, merge: true, using: API::Entities::Address
end
expose :status, merge: trueThis will return something like:
{ contact_info: { phone: "88002000700", city: 'City 17', address_line: 'Block C' }, text: 'HL3', likes: 19 }It also works with collections:
expose :profiles do
expose :users, merge: true, using: API::Entities::User
expose :admins, merge: true, using: API::Entities::Admin
endProvide lambda to solve collisions:
expose :status, merge: ->(key, old_val, new_val) { old_val + new_val if old_val && new_val }Use a block or a Proc to evaluate exposure at runtime. The supplied block or
Proc will be called with two parameters: the represented object and runtime options.
NOTE: A block supplied with no parameters will be evaluated as a nested exposure (see above).
expose :digest do |status, options|
Digest::MD5.hexdigest status.txt
endexpose :digest, proc: ... # equivalent to a blockYou can also define a method on the entity and it will try that before trying on the object the entity wraps.
class ExampleEntity < Grape::Entity
expose :attr_not_on_wrapped_object
# ...
private
def attr_not_on_wrapped_object
42
end
endYou always have access to the presented instance (object) and the top-level
entity options (options).
class ExampleEntity < Grape::Entity
expose :formatted_value
# ...
private
def formatted_value
"+ X #{object.value} #{options[:y]}"
end
endTo undefine an exposed field, use the .unexpose method. Useful for modifying inherited entities.
class UserData < Grape::Entity
expose :name
expose :address1
expose :address2
expose :address_state
expose :address_city
expose :email
expose :phone
end
class MailingAddress < UserData
unexpose :email
unexpose :phone
endIf you want to add one more exposure for the field but don't want the first one to be fired (for instance, when using inheritance), you can use the override flag. For instance:
class User < Grape::Entity
expose :name
end
class Employee < User
expose :name, as: :employee_name, override: true
endUser will return something like this { "name" : "John" } while Employee will present the same data as { "employee_name" : "John" } instead of { "name" : "John", "employee_name" : "John" }.
After exposing the desired attributes, you can choose which one you need when representing some object or collection by using the only: and except: options. See the example:
class UserEntity
expose :id
expose :name
expose :email
end
class Entity
expose :id
expose :title
expose :user, using: UserEntity
end
data = Entity.represent(model, only: [:title, { user: [:name, :email] }])
data.as_jsonThis will return something like this:
{
title: 'grape-entity is awesome!',
user: {
name: 'John Applet',
email: '[email protected]'
}
}Instead of returning all the exposed attributes.
The same result can be achieved with the following exposure:
data = Entity.represent(model, except: [:id, { user: [:id] }])
data.as_jsonExpose under a different name with :as.
expose :replies, using: API::Entities::Status, as: :responsesApply a formatter before exposing a value.
module Entities
class MyModel < Grape::Entity
format_with(:iso_timestamp) do |date|
date.iso8601
end
with_options(format_with: :iso_timestamp) do
expose :created_at
expose :updated_at
end
end
endDefining a reusable formatter between multiples entities:
module ApiHelpers
extend Grape::API::Helpers
Grape::Entity.format_with :utc do |date|
date.utc if date
end
endmodule Entities
class MyModel < Grape::Entity
expose :updated_at, format_with: :utc
end
class AnotherModel < Grape::Entity
expose :created_at, format_with: :utc
end
endBy default, exposures that contain nil values will be represented in the resulting JSON as null.
As an example, a hash with the following values:
{
name: nil,
age: 100
}will result in a JSON object that looks like:
{
"name": null,
"age": 100
}There are also times when, rather than displaying an attribute with a null value, it is more desirable to not display the attribute at all. Using the hash from above the desired JSON would look like:
{
"age": 100
}In order to turn on this behavior for an as-exposure basis, the option expose_nil can be used. By default, expose_nil is considered to be true, meaning that nil values will be represented in JSON as null. If false is provided, then attributes with nil values will be omitted from the resulting JSON completely.
module Entities
class MyModel < Grape::Entity
expose :name, expose_nil: false
expose :age, expose_nil: false
end
endexpose_nil is per exposure, so you can suppress exposures from resulting in null or express null values on a per exposure basis as you need:
module Entities
class MyModel < Grape::Entity
expose :name, expose_nil: false
expose :age # since expose_nil is omitted nil values will be rendered as null
end
endIt is also possible to use expose_nil with with_options if you want to add the configuration to multiple exposures at once.
module Entities
class MyModel < Grape::Entity
# None of the exposures in the with_options block will render nil values as null
with_options(expose_nil: false) do
expose :name
expose :age
end
end
endWhen using with_options, it is possible to again override which exposures will render nil as null by adding the option on a specific exposure.
module Entities
class MyModel < Grape::Entity
# None of the exposures in the with_options block will render nil values as null
with_options(expose_nil: false) do
expose :name
expose :age, expose_nil: true # nil values would be rendered as null in the JSON
end
end
endThis option can be used to provide a default value in case the return value is nil or empty.
module Entities
class MyModel < Grape::Entity
expose :name, default: ''
expose :age, default: 60
end
endExpose documentation with the field. Gets bubbled up when used with Grape and various API documentation systems.
expose :text, documentation: { type: "String", desc: "Status update text." }The option keys :version and :collection are always defined. The :version key is defined as api.version. The :collection key is boolean, and defined as true if the object presented is an array. The options also contain the runtime environment in :env, which includes request parameters in options[:env]['grape.request.params'].
Any additional options defined on the entity exposure are included as is. In the following example user is set to the value of current_user.
class Status < Grape::Entity
expose :user, if: lambda { |instance, options| options[:user] } do |instance, options|
# examine available environment keys with `p options[:env].keys`
options[:user]
end
endpresent s, with: Status, user: current_userSometimes you want to pass additional options or parameters to nested a exposure. For example, let's say that you need to expose an address for a contact info and it has two different formats: full and simple. You can pass an additional full_format option to spec
No open issues yet, or sync has not completed.