Skip to content

Commit c867f28

Browse files
authored
Error serialization documentation in plain Ruby (#27)
Fixes jsonapi-rb/jsonapi-serializable#88
1 parent 5532834 commit c867f28

File tree

1 file changed

+50
-1
lines changed

1 file changed

+50
-1
lines changed

source/guides/getting_started/plain_ruby.html.md.erb

Lines changed: 50 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -42,8 +42,57 @@ renderer.render(posts, relationship: :comments
4242
## Rendering errors
4343

4444
```ruby
45+
class SerializableError < JSONAPI::Serializable::Error
46+
title do
47+
"Invalid #{@field}" unless @field.nil?
48+
end
49+
50+
detail do
51+
@message
52+
end
53+
54+
source do
55+
pointer "/data/attributes/#{@field}" unless @field.nil?
56+
end
57+
end
58+
59+
class SerializableErrors
60+
def initialize(exposures)
61+
@errors = exposures[:object]
62+
freeze
63+
end
64+
65+
def as_jsonapi
66+
@errors.keys.flat_map do |key|
67+
@errors[key].map do |message|
68+
SerializableError.new(
69+
field: key,
70+
message: message
71+
).as_jsonapi
72+
end
73+
end
74+
end
75+
end
76+
77+
4578
renderer = JSONAPI::Serializable::Renderer.new
4679

80+
# errors input signature
81+
# errors = [
82+
# {
83+
# title: [
84+
# "must be filled",
85+
# "size cannot be greater than 100"
86+
# ]
87+
# },
88+
# {
89+
# body: [
90+
# "must be filled",
91+
# "size cannot be less than 3"
92+
# ]
93+
# }
94+
# ]
95+
4796
renderer.render_errors(errors,
48-
class: { Hash: SerializableErrorHash })
97+
class: { Hash: SerializableErrors })
4998
```

0 commit comments

Comments
 (0)