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
として扱いたい。
my_api.rb
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形式を想定している。
lib/ext/active_support/time_with_zone.rb
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
を実装すれば型変換ができる。