Skip to content

Instantly share code, notes, and snippets.

@pewniak747
Last active March 23, 2017 14:59
Show Gist options
  • Save pewniak747/2f38b0fc13252185293a to your computer and use it in GitHub Desktop.
Save pewniak747/2f38b0fc13252185293a to your computer and use it in GitHub Desktop.
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