中村的雑記

技術に関する記事を書いていきます。iOSエンジニア->Railsエンジニア。

Rails2週目: APIの実装、Decorator、パーシャルetc

はじめに

8/11~8/14で経験した内容についてまとめる。今週は初めてAPIの開発をした。

別のAPIでのレスポンスと結構かぶっているところがあったので、レビューをもらいながらパーシャルを活用した。
ちなみにうちはjson周りはjbを使っている。

例の如く変数名とかはぼやかしてる。

APIの開発

Controller内で、最初モデル名をstockの用に単数形で指定してしまっていたが、正解は複数形。

def this_month_payout
    t = Time.zone.now
    stocks   # <= stockにして動かなかった
      .find_by(t.year, t.month)
      .nil ? 0 : :amount
end

また別のControllerで、インスタンス変数を宣言した後利用するときに@をつけ忘れていたが、必要なよう。

def show
   stock = current_user.stocks.find(params[:stock_id])
   @adjustment = stock.adjustment
   @adjustment_amount = @adjustment&.amount || 0
end

ちなみに&.は上の例だともしnilだったら0を、そうじゃなければamountを返すためにつけている。

Decorator

下記で宣言したメソッドを、次で紹介するパーシャルで使っている。 Decoratorを使うことでViewにロジックを書くのを避けられるといったメリットがある。

module UserDecorator
  def id_verification_examination_status
     licences
      .order(created_at: :desc)
      .first
      &.examination_status || :unregistered
  end
  略
end

パーシャルの活用

jsonの中でかぶっているところを_invest_request_detail.json.jbという形で切り出し、 このパーシャルを使いたいところでrenderで呼んで使う。

ちなみに、下記のコードで@のついているインスタンス変数はControllerで宣言している。 下記のような方法でパーシャルを使い、View内で値をいれたjsonを返すということができた。

# frozen_string_literal: true
invest_request_detail = render 'api/v1/invest_requests/invest_request_detail',
                                 invest_request: @invest_request,
                                 id_verification_status: @invest_entry.user.id_verification_examination_status, 
invest_request_detail[:amount] = @amount
invest_request_detail[:adjustments] = @adjustment_amount


invest_request_detail

 

Rspec

あるモデルが存在しないときに、idで0を指定するというテクニックをレビューで教えてもらった。 ちなみにエンドポイントがapi/v1/users/{stock_id}/entries/{id}みたいなとき、下記のコードのgetの行のようにstockを渡せばOK。 最初stock.idとしていた。

let!(:stock) do
      create(:stock)
end

it 'should have 404 when investment_entry not found' do
      get api_v1_me_investment_entry_path(stock, 0),
          headers: {
            'Authorization' => "Bearer #{auth0_id_token}",
          }
      expect(response).to have_http_status(404)
      assert_response_schema_confirm
end

来週にむけて

来週からは日記形式ではなく学んだポイントをまとめていくスタイルにする。

また引き続きこれを進める。(現在50%くらい読んだ)