Grape ::实体自定义响应说明

时间:2015-12-31 10:47:43

标签: ruby-on-rails

我正在使用Grape :: Entity进行自定义响应 但是当我看到文档时 Grape::Entity

它说用grap :: entity我们可以决定运行时哪个属性要发送&不是。 但即使给出提示,我也无法理解CODE

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

expose :digest do |status, options|
    Digest::MD5.hexdigest status.txt
end

如果有人逐行解释,我真的很感激

1 个答案:

答案 0 :(得分:0)

好的,我会试一试。

您应该知道的一件事是,当您在Grape端点中调用Grape :: Entity时,可以将可选属性传递给Grape :: Entity:

present statuses, with: API::Entities::Status, type: :full

您可以将任何内容传递给Entity对象(例如type)。

使用这些可选属性,您可以在实体内部工作。

  • 第1行:如果type的值为:full,则会显示:ip
  • 第2行:与第1行相同,但在lambda中封装。您可以访问块内的instanceoptions哈希。
  • 第3行:如果实体中存在type,则会显示:ip
  • 第4行:与第1行相同
  • 第5行:正如评论所说
  • 第6-8行:这是一个嵌套的实体。 :using声明哪个Entity类用于此公开。该块设置传递给实体的实例,在本例中为status.replies的最后一个对象。
  • 第10-13行:您可以使用with_options块格式化日期或时间对象。在这种情况下,使用:iso_timestamp格式化程序。
  • 第15-17行:这是另一种曝光方式。在此示例中,您将公开status.txt的摘要。

我希望这会以某种方式帮助你。