9
10

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

grapeの入力パラメータでActiveSupport::TimeWithZoneを使用する方法

Posted at

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_atTimeWithZoneとして扱いたい。

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を実装すれば型変換ができる。

9
10
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
9
10

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?