Skip to content

Commit a5d409d

Browse files
committed
Make Errors#as_json act like ActiveModel::Errors
1 parent 1bb7a43 commit a5d409d

File tree

2 files changed

+45
-0
lines changed

2 files changed

+45
-0
lines changed

lib/simple_command/errors.rb

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,18 @@ def full_messages
2424
map { |attribute, message| full_message(attribute, message) }
2525
end
2626

27+
# Allow ActiveSupport to render errors similar to ActiveModel::Errors
28+
def as_json(options = nil)
29+
Hash.new.tap do |output|
30+
raise NotImplementedError.new unless output.respond_to?(:as_json)
31+
32+
self.each do |field, value|
33+
output[field] ||= []
34+
output[field] << value
35+
end
36+
end.as_json(options)
37+
end
38+
2739
private
2840
def full_message(attribute, message)
2941
return message if attribute == :base

spec/simple_command/errors_spec.rb

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -80,6 +80,39 @@
8080
end
8181
end
8282

83+
describe "#as_json" do
84+
it "raises a NotImplementedError" do
85+
expect { errors.as_json }.to raise_error SimpleCommand::NotImplementedError
86+
end
87+
88+
context "when Hash supports as_json" do
89+
module HashAsJsonMixin
90+
# Mock example of as_json from ActiveSupport
91+
def as_json(options)
92+
JSON.parse(to_json(options))
93+
end
94+
end
95+
96+
around do |example|
97+
inject_required = !Hash.new.respond_to?(:as_json)
98+
Hash.include HashAsJsonMixin if inject_required
99+
example.run
100+
Hash.undef_method(:as_json) if inject_required
101+
end
102+
103+
it "groups errors by key values" do
104+
errors.add :attr1, 'has an error'
105+
errors.add :attr2, 'has an error'
106+
errors.add :attr2, 'has two errors'
107+
108+
expect(errors.as_json).to eq(
109+
"attr1" => ["has an error"],
110+
"attr2" => ["has an error", "has two errors"]
111+
)
112+
end
113+
end
114+
end
115+
83116
describe "#to_json" do
84117
it "groups errors by key values" do
85118
errors.add :attr1, 'has an error'

0 commit comments

Comments
 (0)