Albaについて
AlbaはJSONシリアライザーです。
導入方法
以下の手順でRailsのAPIにAlbaを導入できます。
インストールする
Gemfile
に以下のように記述してbundle install
を実行してインストールします。
gem 'alba'
bundle install
設定ファイルを作成する
config/initializer/alba.rb
を以下の内容で作成します。
config/initializer/alba.rb
Alba.backend = :active_support
resourcesディレクトリを作成する
app/resources
ディレクトリを作成し、user_resource.rb
を作成します。
app/resources/user_resource.rb
class UserResource
include Alba::Resource
root_key :user
attributes :id, :name
end
コントローラーを編集する
コントローラーを以下のように編集します。
app/controllers/api/v1/users_controller.rb
module Api
module V1
class UsersController < ApplicationController
def show
user = User.find(params[:id])
render json: UserResource.new(user), status: :ok
end
end
end
end
リクエストする
GET api/v1/users/1
をすると以下のようなレスポンスが返ります。
{
user: {
id: '1',
name: 'sample',
}
}
公式ドキュメント