LoginSignup
0
0

More than 1 year has passed since last update.

【Ruby on Rails】APIのエンドポイントにケバブケース(kebab-case)を設定する

Last updated at Posted at 2022-06-14

この記事について

RailsでAPIを作成する際、エンドポイントを設定しますが、 /api/v1/sample-apis のように複数単語(「sample apis」)の部分はkebab-caseを使用することが多いかと思います。
しかし、Rubyの命名規則的には、ファイル名はsnake_caseかと思いますので、snake_case→kebab-caseの変換を行う必要があります。
この記事では、Railsのエンドポイントでsnake_case→kebab-caseの変換方法を記録として残したいと思います。

コントローラクラスの作成

エンドポイント api/v1/sample-apis に対するコントローラクラスを作成します。
RailsではControllerクラスのフィル名をsnake_caseで記述し、 <エンドポイントのsnake_case>_controller となるため、 sample_apis_controller.rb としております。
api/v1/ の部分はmoduleを使用することとします。

app/controllers/api/v1/sample_apis_controller.rb
module Api
    module V1
        class SampleApisController < ActionController::API
            def index
                render json: {
                    data: { message: 'this is sample apis action' }
                }
            end
        end
    end
end

config/routes.rb でのパス設定

resources にはコントローラクラスのファイル名(から _controller.rb を除いた部分)、:path => にはエンドポイントとして設定したい文字列を記述します。

config/routes.rb
Rails.application.routes.draw do
  namespace :api do
    namespace :v1 do
      resources :sample_apis, :path => 'sample-apis'
    end
  end
end

動作確認

rails s でRailsサーバを起動してブラウザで /api/v1/sample-apis にアクセスしてみます。
(画像では3100ポートを起動していますが、3000ポートを起動している場合は http://localhost:3000/api/v1/sample-apis にアクセスしてください。)
image.png

参考

Routes with Dash - Instead of Underscore _ in Ruby on Rails

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0