25.Ruby-Grape|declared

RubyAPIの処理中でよく出てくる。
ぼんやりした理解だったのでおさらい。

Grape allows you to access only the parameters that have been declared by your params block. It filters out the params that have been passed, but are not allowed. Consider the following API endpoint:

format :json

post 'users/signup' do
  { 'declared_params' => declared(params) }
end

If you do not specify any parameters, declared will return an empty hash.

  • Request
curl -X POST -H "Content-Type: application/json" localhost:9292/users/signup -d '{"user": {"first_name":"first name", "last_name": "last name"}}'
  • Response
{
  "declared_params": {}
}

github.com

APIの定義時に指定するparamsに基づいて、そこで指定されていないものは落とす。

params do
  requires :title, type: String
  requires :content, type: String
  optional :published, type: Boolean
end
…
post do
  article = Article.new(declared(params, include_missing: false))
end

例えば上記の例で、paramsの中でもしtitleが定義されていなければ、
declared(params)の中でtitleのキーとバリューはレスポンスの中に含まれなくなる(落とされる)。
その場合、declared(params)[:title]nilで返ってくる。