Module: RestfulError

Defined in:
lib/restful_error.rb,
lib/restful_error/status.rb,
lib/restful_error/railtie.rb,
lib/restful_error/version.rb,
lib/restful_error/inflector.rb,
lib/restful_error/exceptions_app.rb,
lib/restful_error/exceptions_controller.rb,
lib/restful_error/application_controller.rb

Defined Under Namespace

Modules: Helper, Inflector Classes: ApplicationController, BaseError, ExceptionsApp, ExceptionsController, Railtie

Constant Summary collapse

Status =
Data.define(:code, :reason_phrase, :symbol, :const_name)
STATUS_CODE_TO_SYMBOL =
Rack::Utils::SYMBOL_TO_STATUS_CODE.invert
VERSION =
"1.0.5"

Class Method Summary collapse

Class Method Details

.[](code_like) ⇒ Object



32
33
34
35
# File 'lib/restful_error.rb', line 32

def [](code_like)
  status = RestfulError.build_status_from_symbol_or_code(code_like)
  @cache[status.code] ||= build_error_class_for(status)
end

.build_status_from_const(const_sym) ⇒ Object



11
12
13
14
15
16
# File 'lib/restful_error/status.rb', line 11

def self.build_status_from_const(const_sym)
  const_name = const_sym.to_s
  return unless /[A-Z]/.match?(const_name[0])
  symbol = RestfulError::Inflector.underscore(const_name).to_sym
  build_status_from_symbol_or_code(symbol)
end

.build_status_from_symbol_or_code(code_or_sym) ⇒ Object



17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/restful_error/status.rb', line 17

def self.build_status_from_symbol_or_code(code_or_sym)
  case code_or_sym
  when Integer
    code = code_or_sym
    symbol = STATUS_CODE_TO_SYMBOL[code]
    const_name = Inflector.camelize(symbol.to_s)
    reason_phrase = Rack::Utils::HTTP_STATUS_CODES[code]
    Status.new(code:, symbol:, const_name:, reason_phrase:)
  when Symbol
    begin
      build_status_from_symbol_or_code Rack::Utils.status_code(code_or_sym)
    rescue ArgumentError
      nil
    end
  when /\A\d{3}\z/
    build_status_from_symbol_or_code(code_or_sym.to_i)
  else
    raise ArgumentError, "Invalid argument: #{code_or_sym.inspect}"
  end
end

.const_missing(const_name) ⇒ Object



37
38
39
40
41
42
# File 'lib/restful_error.rb', line 37

def const_missing(const_name)
  status = RestfulError.build_status_from_const(const_name)
  return super unless status

  @cache[status.code] ||= build_error_class_for(status)
end

.init_i18nObject



44
45
46
47
48
# File 'lib/restful_error.rb', line 44

def init_i18n
  return if @init_i18n
  I18n.load_path += Dir["#{File.expand_path("./config/locales")}/*.yml"]
  @init_i18n = true
end

.localized_phrase(class_name, status) ⇒ Object



49
50
51
52
53
54
# File 'lib/restful_error.rb', line 49

def localized_phrase(class_name, status)
  return false unless defined?(I18n)
  init_i18n
  class_key = RestfulError::Inflector.underscore(class_name)
  I18n.t class_key, default: [status.symbol, false], scope: :restful_error
end