Skip to content

Instantly share code, notes, and snippets.

@jb41
Created July 30, 2016 16:49
Show Gist options
  • Save jb41/92c602849d68b7697f1f738c85c3bb70 to your computer and use it in GitHub Desktop.
Save jb41/92c602849d68b7697f1f738c85c3bb70 to your computer and use it in GitHub Desktop.
Dynamically create Error classes
module SheetCRUD
module Error
ERRORS = [
unauthorized: { message: 'Unauthorized.', status: 401 },
limit_exceed: { message: 'Rate limit exceed.', status: 429 },
not_found: { message: 'Not found.', status: 404 }
]
class StandardAPIError < StandardError
attr_reader :status
def initialize(message="Error.", status=500)
@status = status
super(message)
end
end
ERRORS[0].each_pair do |klass_name, values|
klass = Class.new(StandardAPIError) do
define_method :initialize do |message = values[:message], status = values[:status]|
super(message, status)
end
end
Error.const_set(klass_name.to_s.camelize, klass)
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment