Railsとgrapeを使用してWebAPIを作成する。
grapeでは入力パラメータのバリデーションと型変換(文字列からRubyのなんらかのクラスのインスタンス)のためにparamsのブロックの中にtypeを指定することができる。しかし、標準的なものしかサポートされていない。
日付・時刻型はDate, DateTime, Timeが指定できるが、RailsではActiveSupport::TimeWithZoneを使用することが多いだろう。これを指定できるようにする。
バージョンはRuby(2.2), Rails(4.2), grape(0.13.0)で確認した。
例として、次のようなAPIがあったとする。will_publish_atをTimeWithZoneとして扱いたい。
class MyAPI < Grape::API
resource :posts do
params do
requires :title, type: String, allow_blank: false
requires :body, type: String, allow_blank: false
optional :will_publish_at, type: ActiveSupport::TimeWithZone
end
post do
declared_params = declared(params)
# declared_params.will_publish_at が ActiveSupport::TimeWithZoneになっている
# ...省略
end
end
end
そのままだとエラーになるが、次のようにするとよい。なお、will_publish_atはISO8601形式を想定している。
module ActiveSupport
class TimeWithZone
def self.parse(value)
# ここでインスタンスを作成できればなんでもいい
Time.iso8601(value).in_time_zone if value.present?
end
end
end
あとは、これを適切な場所でrequireする。
ActiveSupport::TimeWithZoneにかかわらず、self.parseを実装すれば型変換ができる。