Project Icon

grape-entity

Ruby API响应构建的轻量级实体框架

Grape::Entity是一个为Ruby API框架设计的实体工具,用于构建灵活的响应结构。它支持条件性暴露字段、嵌套实体和集合处理等功能。开发者可使用其简洁DSL定义响应,提高API开发效率。该工具还提供自定义格式化和文档生成功能,可与Grape框架集成使用。

Gem Version Ruby Coverage Status Code Climate

Table of Contents

Grape::Entity

Introduction

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.

Example

module API
  module Entities
    class Status < Grape::Entity
      format_with(:iso_timestamp) { |dt| dt.iso8601 }

      expose :user_name
      expose :text, documentation: { type: "String", desc: "Status update text." }
      expose :ip, if: { type: :full }
      expose :user_type, :user_id, if: lambda { |status, options| status.user.public? }
      expose :location, merge: true
      expose :contact_info do
        expose :phone
        expose :address, merge: true, using: API::Entities::Address
      end
      expose :digest do |status, options|
        Digest::MD5.hexdigest status.txt
      end
      expose :replies, using: API::Entities::Status, as: :responses
      expose :last_reply, using: API::Entities::Status do |status, options|
        status.replies.last
      end

      with_options(format_with: :iso_timestamp) do
        expose :created_at
        expose :updated_at
      end
    end
  end
end

module API
  module Entities
    class StatusDetailed < API::Entities::Status
      expose :internal_id
    end
  end
end

Reusable Responses with Entities

Entities are a reusable means for converting Ruby objects to API responses. Entities can be used to conditionally include fields, nest other entities, and build ever larger responses, using inheritance.

Defining Entities

Entities inherit from Grape::Entity, and define a simple DSL. Exposures can use runtime options to determine which fields should be visible, these options are available to :if, :unless, and :proc.

Basic Exposure

Define a list of fields that will always be exposed.

expose :user_name, :ip

The field lookup takes several steps

  • first try entity-instance.exposure
  • next try object.exposure
  • next try object.fetch(exposure)
  • last raise an Exception

exposure is a Symbol by default. If object is a Hash with stringified keys, you can set the hash accessor at the entity-class level to properly expose its members:

class Status < GrapeEntity
  self.hash_access = :to_s

  expose :code
  expose :message
end

Status.represent({ 'code' => 418, 'message' => "I'm a teapot" }).as_json
#=> { code: 418, message: "I'm a teapot" }

Exposing with a Presenter

Don't derive your model classes from Grape::Entity, expose them using a presenter.

expose :replies, using: API::Entities::Status, as: :responses

Presenter classes can also be specified in string format, which helps with circular dependencies.

expose :replies, using: "API::Entities::Status", as: :responses

Conditional Exposure

Use :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 :if

Safe Exposure

Don't raise an exception and expose as nil, even if the :x cannot be evaluated.

expose :ip, safe: true

Nested Exposure

Supply a block to define a hash using nested exposures.

expose :contact_info do
  expose :phone
  expose :address, using: API::Entities::Address
end

You 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 }
end

Collection Exposure

Use 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


Merge Fields

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: true

This 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
end

Provide lambda to solve collisions:

expose :status, merge: ->(key, old_val, new_val) { old_val + new_val if old_val && new_val }

Runtime Exposure

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
end
expose :digest, proc: ... # equivalent to a block

You 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
end

You 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
end

Unexpose

To 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
end

Overriding exposures

If 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
end

User 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" }.

Returning only the fields you want

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_json

This will return something like this:

{
  title: 'grape-entity is awesome!',
  user: {
    name: 'John Applet',
    email: 'john@example.com'
  }
}

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_json

Aliases

Expose under a different name with :as.

expose :replies, using: API::Entities::Status, as: :responses

Format Before Exposing

Apply 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
end

Defining a reusable formatter between multiples entities:

module ApiHelpers
  extend Grape::API::Helpers

  Grape::Entity.format_with :utc do |date|
    date.utc if date
  end
end
module Entities
  class MyModel < Grape::Entity
    expose :updated_at, format_with: :utc
  end

  class AnotherModel < Grape::Entity
    expose :created_at, format_with: :utc
  end
end

Expose Nil

By 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
end

expose_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
end

It 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
end

When 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
end

Default Value

This 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
end

Documentation

Expose 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." }

Options Hash

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
end
present s, with: Status, user: current_user

Passing Additional Option To Nested Exposure

Sometimes 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 specify which format to render.

# api/contact.rb
expose :contact_info do
  expose :phone
  expose :address do |instance, options|
    # use `#merge` to extend options and then pass the new version of options to the nested entity
    API::Entities::Address.represent instance.address, options.merge(full_format: instance.need_full_format?)
  end
  expose :email, if: lambda { |instance, options| options[:type] == :full }
end

# api/address.rb
expose :state, if: lambda {|instance, options| !!options[:full_format]}      # the new option could be retrieved in options hash for conditional exposure
expose :city, if: lambda {|instance, options| !!options[:full_format]}
expose :street do |instance, options|
  # the new option could be retrieved in options hash for runtime exposure
  !!options[:full_format] ? instance.full_street_name : instance.simple_street_name
end

Notice: In the above code, you should pay attention to Safe Exposure yourself. For example, instance.address might be nil and it is better to expose it as nil directly.

Attribute Path Tracking

Sometimes, especially when there are nested attributes,

项目侧边栏1项目侧边栏2
推荐项目
Project Cover

豆包MarsCode

豆包 MarsCode 是一款革命性的编程助手,通过AI技术提供代码补全、单测生成、代码解释和智能问答等功能,支持100+编程语言,与主流编辑器无缝集成,显著提升开发效率和代码质量。

Project Cover

AI写歌

Suno AI是一个革命性的AI音乐创作平台,能在短短30秒内帮助用户创作出一首完整的歌曲。无论是寻找创作灵感还是需要快速制作音乐,Suno AI都是音乐爱好者和专业人士的理想选择。

Project Cover

白日梦AI

白日梦AI提供专注于AI视频生成的多样化功能,包括文生视频、动态画面和形象生成等,帮助用户快速上手,创造专业级内容。

Project Cover

有言AI

有言平台提供一站式AIGC视频创作解决方案,通过智能技术简化视频制作流程。无论是企业宣传还是个人分享,有言都能帮助用户快速、轻松地制作出专业级别的视频内容。

Project Cover

Kimi

Kimi AI助手提供多语言对话支持,能够阅读和理解用户上传的文件内容,解析网页信息,并结合搜索结果为用户提供详尽的答案。无论是日常咨询还是专业问题,Kimi都能以友好、专业的方式提供帮助。

Project Cover

讯飞绘镜

讯飞绘镜是一个支持从创意到完整视频创作的智能平台,用户可以快速生成视频素材并创作独特的音乐视频和故事。平台提供多样化的主题和精选作品,帮助用户探索创意灵感。

Project Cover

讯飞文书

讯飞文书依托讯飞星火大模型,为文书写作者提供从素材筹备到稿件撰写及审稿的全程支持。通过录音智记和以稿写稿等功能,满足事务性工作的高频需求,帮助撰稿人节省精力,提高效率,优化工作与生活。

Project Cover

阿里绘蛙

绘蛙是阿里巴巴集团推出的革命性AI电商营销平台。利用尖端人工智能技术,为商家提供一键生成商品图和营销文案的服务,显著提升内容创作效率和营销效果。适用于淘宝、天猫等电商平台,让商品第一时间被种草。

Project Cover

AIWritePaper论文写作

AIWritePaper论文写作是一站式AI论文写作辅助工具,简化了选题、文献检索至论文撰写的整个过程。通过简单设定,平台可快速生成高质量论文大纲和全文,配合图表、参考文献等一应俱全,同时提供开题报告和答辩PPT等增值服务,保障数据安全,有效提升写作效率和论文质量。

投诉举报邮箱: service@vectorlightyear.com
@2024 懂AI·鲁ICP备2024100362号-6·鲁公网安备37021002001498号