Class: JsendWrapper::ErrorRenderer

Inherits:
Renderer
  • Object
show all
Defined in:
lib/jsend_wrapper/renderers/error_renderer.rb

Overview

Wraps the given message in a JSend Error. JSend Errors have two required elements (status, message) and two optional elements (code, data).

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(message, optional = {}) ⇒ ErrorRenderer

Returns a new instance of ErrorRenderer.

Parameters:

  • message (#to_s)
  • optional (Hash) (defaults to: {})

    the optional elements

Options Hash (optional):

  • :code (#to_i)

    a numeric code representing the error

  • :data (Object)

    a generic container for any other information about the error



32
33
34
35
36
37
38
39
# File 'lib/jsend_wrapper/renderers/error_renderer.rb', line 32

def initialize(message, optional={})
  @message  = message.to_s
  @has_code = optional.key? :code
  @has_data = optional.key? :data

  @code = parse_code optional[:code] if code?
  @data = optional[:data]            if data?
end

Instance Attribute Details

#codeObject (readonly)

Returns the value of attribute code.



22
23
24
# File 'lib/jsend_wrapper/renderers/error_renderer.rb', line 22

def code
  @code
end

#dataObject (readonly)

Returns the value of attribute data.



22
23
24
# File 'lib/jsend_wrapper/renderers/error_renderer.rb', line 22

def data
  @data
end

#has_codeObject (readonly) Also known as: code?

Returns the value of attribute has_code.



22
23
24
# File 'lib/jsend_wrapper/renderers/error_renderer.rb', line 22

def has_code
  @has_code
end

#has_dataObject (readonly) Also known as: data?

Returns the value of attribute has_data.



22
23
24
# File 'lib/jsend_wrapper/renderers/error_renderer.rb', line 22

def has_data
  @has_data
end

#messageObject (readonly)

Returns the value of attribute message.



22
23
24
# File 'lib/jsend_wrapper/renderers/error_renderer.rb', line 22

def message
  @message
end

Instance Method Details

#to_hObject



47
48
49
50
51
52
# File 'lib/jsend_wrapper/renderers/error_renderer.rb', line 47

def to_h
  {status: 'error', message: message}.tap do |hash|
    hash[:code] = code if code?
    hash[:data] = data if data?
  end
end

#to_sString

Returns the rendered JSON.

Returns:

  • (String)

    the rendered JSON



43
44
45
# File 'lib/jsend_wrapper/renderers/error_renderer.rb', line 43

def to_s
  %[{"status":"error","message":#{message.inspect}#{optional}}]
end