fujjima blog
  • 経歴
  • 問い合わせ

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形式で格納されている。

参考:

  • https://www.rubydoc.info/github/intridea/grape-entity/Grape%2FEntity.represent
  • https://blog.kyanny.me/entry/2015/11/22/224607

月別アーカイブ

  • ▶︎ ▼
    2025 (2)
    2025/01 (2)
  • ▶︎ ▼
    2024 (1)
    2024/01 (1)
  • ▶︎ ▼
    2023 (1)
    2023/05 (1)
  • ▶︎ ▼
    2022 (1)
    2022/10 (1)
  • ▶︎ ▼
    2021 (10)
    2021/11 (1)
    2021/09 (1)
    2021/08 (2)
    2021/05 (1)
    2021/03 (1)
    2021/02 (1)
    2021/01 (3)
  • ▶︎ ▼
    2020 (9)
    2020/12 (3)
    2020/11 (1)
    2020/07 (4)
    2020/01 (1)
  • ▶︎ ▼
    2019 (9)
    2019/12 (1)
    2019/10 (1)
    2019/08 (2)
    2019/07 (1)
    2019/06 (1)
    2019/05 (1)
    2019/02 (1)
    2019/01 (1)
  • ▶︎ ▼
    2018 (11)
    2018/11 (1)
    2018/10 (1)
    2018/09 (1)
    2018/08 (1)
    2018/06 (1)
    2018/05 (1)
    2018/04 (2)
    2018/02 (1)
    2018/01 (2)
  • ▶︎ ▼
    2017 (1)
    2017/12 (1)


  • タグ

    プログラミング
    読書
    備忘録
    chrome拡張
    gem
    rails
    フリーランス
    服
    その他