ruby - 如何在 Ruby + Grape API 中使所有时间输出成为 ISO 8601

标签 ruby monkeypatching iso8601 ruby-grape

我一直在寻找最简单的解决方案,以便在将所有日期时间值从 API 发送给特定请求者时将它们转换为 ISO 8601。我能够使用以下代码修改Time#to_json:

class Time
  def to_json(options = {})
    self.iso8601.to_json
  end
end

当参数显示请求来自所需位置时,在 Grape 的 before 回调中要求文件。

这是实现此目标的最佳方式吗?我是否可以在 Grape 的 after 回调中做一些事情来循环遍历我的数据并在那里转换值?猴子修补 Time#to_json 完成了工作,但我觉得很有趣。虽然我是 Ruby 的新手。

最佳答案

您是否正在使用 Grape Entity 公开您的模型?如果您正在使用它,那么您可以像这样定义一个可重用的格式化程序:

module ApiHelpers
  extend Grape::API::Helpers

  Grape::Entity.format_with :iso8601 do |date|
    date.iso8601 if date
  end
end

然后,您可以在所有实体中使用此格式化程序:

module Entities
  class MyModel < Grape::Entity
    expose :updated_at, format_with: :iso8601
  end

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

但是,如果您不使用 Grape Entity……好吧,我认为您应该这样做。 :)

PS.:我在这里展示的所有例子都是从 Grape Entity 文档中提取的。 https://github.com/ruby-grape/grape-entity

关于ruby - 如何在 Ruby + Grape API 中使所有时间输出成为 ISO 8601,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37534344/

相关文章:

Ruby-on-rails Postgres 查询

ruby-on-rails - 如何从现有的 Time.zone for Rails 创建 Ruby DateTime?

ruby - 不能在 Alpine Linux 上要求 ruby​​ gsl

python - 如何为多个测试打补丁

c# 将日期时间对象转换为 iso 8601 字符串

javascript - 添加不需要用户模型的“赞”按钮

apache-flex - 修补 flex 框架以立即显示预加载器?

python - 如何扩展类实例

date - 如何在 Swift 中解析/创建格式为小数秒 UTC 时区(ISO 8601、RFC 3339)的日期时间戳?

excel - 在 Excel 中解析 ISO8601 日期/时间(包括时区)