Class: ServiceObject::Errors

Inherits:
Delegator
  • Object
show all
Defined in:
lib/service_object/errors.rb

Overview

Provides a customized Array to contain errors that happen in service layer. Also provides a utility APIs to handle errors well in controllers. (All array methods are available by delegation, too.)

 errs = ServiceObject::Errors.new
 errs.add 'Something is wrong.'
 errs.add 'Another is wrong.'
 errs.messages
 => ['Something is wrong.','Another is wrong.']
 errs.full_messages
 => ['Something is wrong.','Another is wrong.']
 errs.to_xml
 => "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<errors>\n  <error>Something is wrong.</error>\n
<error>Another is wrong.</error>\n</errors>\n"
 errs.empty?
 => false
 errs.clear
 => []
 errs.empty?
 => true

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeErrors

Returns a new instance of Errors.



29
30
31
# File 'lib/service_object/errors.rb', line 29

def initialize
  @messages = []
end

Instance Attribute Details

#messagesArray<String> (readonly)

Returns Messages of the current errors.

Returns:

  • (Array<String>)

    Messages of the current errors



27
28
29
# File 'lib/service_object/errors.rb', line 27

def messages
  @messages
end

Instance Method Details

#__getobj__Object



34
35
36
# File 'lib/service_object/errors.rb', line 34

def __getobj__ # :nodoc:
  @messages
end

#add(message) ⇒ Object

Adds a new error message to the current error messages

Parameters:

  • message (String)

    New error message to add



46
47
48
# File 'lib/service_object/errors.rb', line 46

def add(message)
  @messages << message
end

#as_jsonArray<String>

Generates duplication of the message

Returns:

  • (Array<String>)


68
69
70
# File 'lib/service_object/errors.rb', line 68

def as_json
  messages.dup
end

#full_messagesArray<String>

Returns all the current error messages

Returns:

  • (Array<String>)

    Messages of the current errors



40
41
42
# File 'lib/service_object/errors.rb', line 40

def full_messages
  messages
end

#to_xml(options = {}) ⇒ String

Generates XML format errors

errs = ServiceObject::Errors.new
errs.add 'Something is wrong.'
errs.add 'Another is wrong.'
errs.to_xml
=>
<?xml version=\"1.0\" encoding=\"UTF-8\"?>
 <errors>
   <error>Something is wrong.</error>
   <error>Another is wrong.</error>
 </errors>

Returns:

  • (String)

    XML format string



62
63
64
# File 'lib/service_object/errors.rb', line 62

def to_xml(options={})
  super({ root: "errors", skip_types: true }.merge!(options))
end