Skip to content

Instantly share code, notes, and snippets.

@alxekb
Last active June 28, 2020 09:16
Show Gist options
  • Save alxekb/e36a3ee8e18f94d647ffeeb7ac4ecce3 to your computer and use it in GitHub Desktop.
Save alxekb/e36a3ee8e18f94d647ffeeb7ac4ecce3 to your computer and use it in GitHub Desktop.
# frozen_string_literal: true
# Abstract service class
class AbstractService
class << self
def call(*args, &block)
new(*args, &block).call
end
end
def call
raise NotImplementedError, 'Dont instantiate AbstractService, please, work with descendants'
end
def success?
@status == :success
end
end
# frozen_string_literal: true
module Api
module V1
# graceful API errors handling
class Error < StandardError
# class << self
def self.not_found(record = 'record')
{
"status" => 'error',
"code" => 404,
"message" => Message.not_found(record),
"data" => {}
}
end
def self.bad_request(message = '')
{
"status" => 'error',
"code" => 400,
"message" => Message.bad_request(message),
"data" => {}
}
end
def self.parameter_missing
{
"status" => 'error',
"code" => 400,
"message" => Message.parameter_missing,
"data" => {}
}
end
def self.access_denied
{
"status" => 'error',
"code" => 403,
"message" => Message.access_denied,
"data"=> {}
}
end
def self.unauthorized
{
"status" => 'error',
"code" => 401,
"message" => Message.not_authorized,
"data" => {}
}
end
end
end
end
# frozen_string_literal: true
class Message
class << self
def not_found(record = 'record')
"Sorry, #{record} is not found"
end
def not_authorized
'You are not authorized.'
end
def access_denied
'Access denied'
end
def bad_request(parameter = '')
"Bad request #{parameter}"
end
def parameter_missing(parameter = 'parameter')
"#{parameter} is missing"
end
end
end
module Response
def json_response(object, status = :ok)
render json: object, status: status
end
def json(object, status = :ok)
{
data: object,
status: status
}
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment