なんとなく日々徒然と

grape-jbuilderでtimezoneをなんとかする

Grapeでtimezoneを考慮して日付を返す場合は
この What is the best way to emulate around_filter when using Grape?のようにgrapeのbeforeとafterを使って設定するのが定石な気がしますが。
grape-jbuilderでjbuilderの中で書いた日付がbeforeで設定したtimezoneで表示してくれなかったので対応しました。

grapeのendpoint(controllerでいうactionみたいな)で返すとtimezoneが考慮されていますが、jbuilderの中では考慮されていないっぽい。
before -> grapeのendpointの処理 -> after -> jbuilderのrender
という順番で動いているからですね。

苦しいですがrenderの前後にtimezoneを変更するpatchをあてます。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
# config/initializers/grape_jbuilder_patch.rb
module GrapeJbuilderPatch
  def call
    Time.zone = endpoint.current_user.time_zone # ユーザーのtimezoneを使う
    result = super
    Time.zone = Rails.configuration.time_zone # 戻す
    result
  end
end

module Grape
  module Formatter
    class Jbuilder
      prepend GrapeJbuilderPatch
    end
  end
end

Tags:

太東 イシモチ 江戸川放水路 ハゼ

comments powered by Disqus