grapeのoptionsについての備忘録
2021/09/26 22:41
プログラミング, 備忘録
railsのgemに grapeと grape-entityというものがある。
これらを使えば、RESTfulなAPIをそれなりに手軽に返せる機構を作ることが出来る。
以下のようなgrapeのフォーマットに従ったAPIレスポンス用のクラス、及び Entity定義用のクラスがあったとする。
# UserAPIクラス
class Api < Grape::API
format :json
content_type :json, 'application/json'
resource :users do
desc 'user list'
get do
# アクティブ状態のuserを一覧取得するイメージ
users = User.active
# UserEntity.represent(users) = UserEntity.new(users)
UserEntity.represent(users, class: request.headers[:class])
end
end
end
# UserEntityクラス
class UserEntity < Grape::Entity
expose :id
expose :email
expose :status
expose :class_name
private
def class
# object: Userの1インスタンスが入る
object.class_users.find { |class| class.id == @options[:class].id }
end
end
この時、 UserEntity
にて @optionsというインスタンス変数が使われているが、この中には
UserEntity.represent(users, class: request.headers[:class])
で指定された class: request.headers[:class]
部分がkey-value形式で格納されている。
参考: