Skip to content

Commit ef44d26

Browse files
committed
Make Errors#as_json act like ActiveModel::Errors
1 parent c3c3fe7 commit ef44d26

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
@@ -68,6 +68,39 @@
6868
end
6969
end
7070

71+
describe "#as_json" do
72+
it "raises a NotImplementedError" do
73+
expect { errors.as_json }.to raise_error SimpleCommand::NotImplementedError
74+
end
75+
76+
context "when Hash supports as_json" do
77+
module HashAsJsonMixin
78+
# Mock example of as_json from ActiveSupport
79+
def as_json(options)
80+
JSON.parse(to_json(options))
81+
end
82+
end
83+
84+
around do |example|
85+
inject_required = !Hash.new.respond_to?(:as_json)
86+
Hash.include HashAsJsonMixin if inject_required
87+
example.run
88+
Hash.undef_method(:as_json) if inject_required
89+
end
90+
91+
it "groups errors by key values" do
92+
errors.add :attr1, 'has an error'
93+
errors.add :attr2, 'has an error'
94+
errors.add :attr2, 'has two errors'
95+
96+
expect(errors.as_json).to eq(
97+
"attr1" => ["has an error"],
98+
"attr2" => ["has an error", "has two errors"]
99+
)
100+
end
101+
end
102+
end
103+
71104
describe "#to_json" do
72105
it "groups errors by key values" do
73106
errors.add :attr1, 'has an error'

0 commit comments

Comments
 (0)