Last active
March 23, 2017 14:59
-
-
Save pewniak747/2f38b0fc13252185293a to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class APIResponder < ActionController::Responder | |
private | |
def display(resource, options = {}) | |
super(resource.data, options) | |
end | |
def has_errors? | |
!resource.success? | |
end | |
def json_resource_errors | |
{ error: resource.error, message: resource.error_message, code: resource.code, details: resource.details } | |
end | |
def api_location | |
nil | |
end | |
end | |
class Success | |
attr_reader :data | |
def initialize(data) | |
@data = data | |
end | |
def success? | |
true | |
end | |
end | |
class Error | |
attr_reader :error, :code, :details | |
def initialize(error = nil, code = nil, details = nil) | |
@error = error | |
@code = code | |
@details = details | |
end | |
def error_message | |
error.to_s | |
end | |
def success? | |
false | |
end | |
end | |
class ValidationError < Error | |
def initialize(details) | |
super(:validation_failed, 101, details) | |
end | |
def error_message | |
"Validation failed: see details" | |
end | |
end | |
class InvoicesController < ApplicationController | |
respond_to :json | |
def create | |
form = InvoiceForm.new(params) | |
result = CreateInvoice.new(current_user, form).call # => ValidationError.new(invoice.errors) | |
respond_with result # { error: "validation_error", code: 101, message: "..." details: { ... } } | |
end | |
def update | |
result = UpdateInvoice.new(current_user, params[:id]).call # => Success.new(invoice) | |
respond_with(result) # { billing_date: ..., company_name: ... } | |
end | |
# ... | |
def self.responder | |
APIResponder | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment