railsのgemに [grape](https://github.com/ruby-grape/grape)と [grape-entity](https://github.com/ruby-grape/grape-entity#options-hash)というものがある。 これらを使えば、RESTfulなAPIをそれなりに手軽に返せる機構を作ることが出来る。 以下のようなgrapeのフォーマットに従ったAPIレスポンス用のクラス、及び Entity定義用のクラスがあったとする。 ``` ruby # 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 ``` ``` ruby # 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というインスタンス変数が使われているが、この中には ``` ruby UserEntity.represent(users, class: request.headers[:class]) ``` で指定された `class: request.headers[:class]`部分がkey-value形式で格納されている。 参考: - https://www.rubydoc.info/github/intridea/grape-entity/Grape%2FEntity.represent - https://blog.kyanny.me/entry/2015/11/22/224607