A Rails plugin for elegant, hash-based response wrapper for clean Rails API responses.
RailsWarp is automatically included into ActionController and Jbuilder. You don't need to include any module manually.
Call ok and fail directly in your controllers:
class UsersController < ApplicationController
def show
user = User.find(params[:id])
ok data: { user: user }
end
def create
user = User.new(user_params)
if user.save
ok data: { user: user }, message: "created", code: 201
else
fail message: "validation error", code: 422, data: { errors: user.errors.full_messages }
end
end
enddata- The response data (any JSON-serializable object)message- Optional custom message (defaults tonullif not provided)code- HTTP status code (default:200for ok,500for fail)- Additional keyword arguments are merged into the response
{
"success": true,
"code": 200,
"message": "success",
"data": { ... }
}200,201,204: returned as-is400: bad_request401: unauthorized403: forbidden404: not_found422: unprocessable_entity500: internal_server_error
class ApplicationController < ActionController::Base
rescue_from ActiveRecord::RecordNotFound do |e|
fail message: e.message, code: 404
end
rescue_from StandardError do |e|
fail message: "internal error", code: 500, data: { error: e.class.name }
end
endUse json.ok and json.fail in your Jbuilder templates:
# app/views/users/show.json.jbuilder
json.ok message: "User found", code: 200
json.data do
json.id @user.id
json.name @user.name
end
# app/views/shared/error.json.jbuilder
json.fail message: "not found", code: 404
json.data do
json.resource "User"
end# app/views/users/index.json.jbuilder
json.ok message: "Users retrieved", code: 200
json.data do
json.array! @users, partial: "users/user", as: :user
endAdditional keyword arguments are merged into the response root:
json.ok data: { list: @items }, meta: { total: @items.count }You can also use json.warp_ok and json.warp_fail as aliases.
Add this line to your application's Gemfile:
gem "rails_warp"And then execute:
$ bundleOr install it yourself as:
$ gem install rails_warpContribution directions go here.
The gem is available as open source under the terms of the MIT License.