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 < 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
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.
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
.
Define a list of fields that will always be exposed.
expose :user_name, :ip
The field lookup takes several steps
entity-instance.exposure
object.exposure
object.fetch(exposure)
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" }
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
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
Don't raise an exception and expose as nil, even if the :x cannot be evaluated.
expose :ip, safe: true
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
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
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 }
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
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
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" }
.
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
Expose under a different name with :as
.
expose :replies, using: API::Entities::Status, as: :responses
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
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
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
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." }
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
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.
Sometimes, especially when there are nested attributes,
字节跳动发布的AI编程神器IDE
Trae是一种自适应的集成开发环境(IDE),通过自动化和多元协作改变开发流程。利用Trae,团队能够更快速、精确地编写和部署代码,从而提高编程效率和项目交付速度。Trae具备上下文感知和代码自动完成功能,是提升开发效率的理想工具。
全能AI智能助手,随时解答生活与工作的多样问题
问小白,由元石科技研发的AI智能助手,快速准确地解答各种生活和工作问题,包括但不限于搜索、规划和社交互动,帮助用户在日常生活中提高效率,轻松管理个人事务。
实时语音翻译/同声传译工具
Transly是一个多场景的AI大语言模型驱动的同声传译、专业翻译助手,它拥有超精准的音频识别翻译能力,几乎零延迟的使用体验和支持多国语言可以让你带它走遍全球,无论你是留学生、商务人士、韩剧美剧爱好者,还是出国游玩、多国会议、跨国追星等等,都可以满足你所有需要同传的场景需求,线上线下通用,扫除语言障碍,让全世界的语言交流不再有国界。
一键生成PPT和Word,让学习生活更轻松
讯飞智文是一个利用 AI 技术的项目,能够帮助用户生成 PPT 以及各类文档。无论是商业领域的市场分析报告、年度目标制定,还是学生群体的职业生涯规划、实习避坑指南,亦或是活动策划、旅游攻略等内容,它都能提供支持,帮助用户精准表达,轻松呈现各种信息。
深度推理能力全新升级,全面对标OpenAI o1
科大讯飞的星火大模型,支持语言理解、知识问答和文本创作等多功能,适用于多种文件和业务场景,提升办公和日常生活的效率。讯飞星火是一个提供丰富智能服务的平台,涵盖科技资讯、图像创作、写作辅助、编程解答、科研文献解读等功能,能为不同需求的用户提供便捷高效的帮助,助力用户轻松获取信息、解决问题,满足多样化使用场景。
一种基于大语言模型的高效单流解耦语音令牌文本到语音合成模型
Spark-TTS 是一个基于 PyTorch 的开源文本到语音合成项目,由多个知名机构联合参与。该项目提供了高效的 LLM(大语言模型)驱动的语音合成方案,支持语音克隆和语音创建功能,可通过命令行界面(CLI)和 Web UI 两种方式使用。用户可以根据需求调整语音的性别、音高、速度等参数,生成高质量的语音。该项目适用于多种场景,如有声读物制作、智能语音助手开发等。
AI助力,做PPT更简单!
咔片是一款轻量化在线演示设计工具,借助 AI 技术,实现从内容生成到智能设计的一站式 PPT 制作服务。支持多种文档格式导入生成 PPT,提供海量模板、智能美化、素材替换等功能,适用于销售、教师、学生等各类人群,能高效制作出高品质 PPT,满足不同场景演示需求。
选题、配图、成文,一站式创作,让内容运营更高效
讯飞绘文,一个AI集成平台,支持写作、选题、配图、排版和发布。高效生成适用于各类媒体的定制内容,加速品牌传播,提升内容营销效果。
专业的AI公文写作平台,公文写作神器
AI 材料星,专业的 AI 公文写作辅助平台,为体制内工作人员提供高效的公文写作解决方案。拥有海量公文文库、9 大核心 AI 功能,支持 30 + 文稿类型生成,助力快速完成领导讲话、工作总结、述职报告等材料,提升办公效率,是体制打工人的得力写作神器。
OpenAI Agents SDK,助力开发者便捷使用 OpenAI 相关功能。
openai-agents-python 是 OpenAI 推出的一款强大 Python SDK,它为开发者提供了与 OpenAI 模型交互的高效工具,支持工具调用、结果处理、追踪等功能,涵盖多种应用场景,如研究助手、财务研究等,能显著提升开发效率,让开发者更轻松地利用 OpenAI 的技术优势。
最新AI工具、AI资讯
独家AI资源、AI项目落地
微信扫一扫关注公众号