Techioz Blog

RailsでAPIシリアライザー応答のUTC形式を設定するにはどうすればよいですか?

概要

ロンドンゾーンで申請時間を設定しました

config.time_zone = 'London'

ただし、夏時間の問題を避けるために、API 応答の日時を UTC 形式で返す必要があります。

API コントローラーのみのタイムゾーンを変更してみました - API 応答の UTC 時間を設定するための before アクションを追加しました

 api_controller.rb

 before_action :set_utc_time

 def set_utc_time
  Time.zone = 'UTC'
 end

ただし、Webアプリケーションの応答にも反映されているようで、アプリケーション全体でロンドンのタイムゾーンがUTCに変更されます。

response_formatter.rb

Time.use_zone('UTC') do
render json: response_data, status: :ok
end

そこで、ブロック内にタイムゾーンを設定してシリアライザー応答フォーマッタのタイムゾーンを実行しようとしましたが、うまくいかないようです

注: fast_json_api シリアライザーを使用しています

sample serialiser:

class LinguistUnavailabilitySerializer
  include FastJsonapi::ObjectSerializer
  attributes :id, :linguist_id, :departure_time, :return_time, :reason
end

API レスポンスのみに UTC タイムゾーン形式を設定する必要がありますが、アプリケーションのタイムゾーンには反映されないはずです

何か案は ?

解決策

時間属性の属性を再定義してみてはいかがでしょうか https://translate.google.com/translate?hl=ja&sl=en&tl=ja&u=https://github.com/Netflix/fast_jsonapi#attributes そして、メソッドzone_offsetを使用して、現地時間と新しいタイムゾーンの間の加算を行います 例えば

sample serialiser:

class LinguistUnavailabilitySerializer
  include FastJsonapi::ObjectSerializer
  attributes :id, :linguist_id, :departure_time, :return_time, :reason

  attribute :departure_time do |object|
    a = %w(%Y %m %d %H %M %S)
    # ["%Y", "%m", "%d", "%H", "%M", "%S"]
    tm = departure_time
    # 2014-11-03 17:46:02 +0530
    a.map { |s| tm.strftime(s) }
    # ["2014", "11", "03", "17", "46", "02"]
    a.map! { |s| tm.strftime(s).to_i }
    # [2014, 11, 3, 17, 46, 2]
    Time.new(*a, Time.zone_offset('PST'))
  end
end

https://stackoverflow.com/a/26714154/10124678 に基づく変換時間