This repository has been archived by the owner on Sep 28, 2018. It is now read-only.
/
errors.rb
84 lines (79 loc) · 1.88 KB
/
errors.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
module ActiveRecord
# Extension for ActiveRecord::Errors to provie more information to flexible rich client
class Errors
# original :
# <errors>
# <error>message</error>
# <error>message</error>
# ...
# </errors>
# will be changed to : (Not implemented yet)
# <errors>
# <error>
# <attr>attr</attr>
# <message>message</message>
# </error>
# <error>
# <attr>attr</attr>
# <message>message</message>
# </error>
# ...
# </errors>
#
def to_xml(options={})
options[:root] ||= "errors"
options[:indent] ||= 2
options[:builder] ||= Builder::XmlMarkup.new(:indent => options[:indent])
options[:builder].instruct! unless options.delete(:skip_instruct)
options[:builder].errors do |e|
each_attr_message do |attr, msg|
e.error do |detail|
if attr.nil?
detail.message(msg)
else
detail.attr(attr)
detail.message(msg)
end
end
end
end
end
# {
# errors : [
# { attr
# ]
# }
#
#
def to_json
self.to_hash.to_json
end
def to_hash
array = []
each_attr_message do |attr, msg|
if attr.nil?
array << { :message => msg }
else
array << {
:message => msg,
:attr => attr
}
end
end
{ :errors => array }
end
private
def each_attr_message
@errors.each_key do |attr|
@errors[attr].each do |msg|
next if msg.nil?
if attr == "base"
yield nil, (@base.class.human_attribute_name(attr) + " " + msg)
else
yield attr, (@base.class.human_attribute_name(attr) + " " + msg)
end
end
end
end
end
end