Skip to content

Commit

Permalink
Make Errors#as_json act like ActiveModel::Errors
Browse files Browse the repository at this point in the history
  • Loading branch information
bmorrall committed May 18, 2022
1 parent 1bb7a43 commit a5d409d
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 0 deletions.
12 changes: 12 additions & 0 deletions lib/simple_command/errors.rb
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,18 @@ def full_messages
map { |attribute, message| full_message(attribute, message) }
end

# Allow ActiveSupport to render errors similar to ActiveModel::Errors
def as_json(options = nil)
Hash.new.tap do |output|
raise NotImplementedError.new unless output.respond_to?(:as_json)

self.each do |field, value|
output[field] ||= []
output[field] << value
end
end.as_json(options)
end

private
def full_message(attribute, message)
return message if attribute == :base
Expand Down
33 changes: 33 additions & 0 deletions spec/simple_command/errors_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,39 @@
end
end

describe "#as_json" do
it "raises a NotImplementedError" do
expect { errors.as_json }.to raise_error SimpleCommand::NotImplementedError
end

context "when Hash supports as_json" do
module HashAsJsonMixin
# Mock example of as_json from ActiveSupport
def as_json(options)
JSON.parse(to_json(options))
end
end

around do |example|
inject_required = !Hash.new.respond_to?(:as_json)
Hash.include HashAsJsonMixin if inject_required
example.run
Hash.undef_method(:as_json) if inject_required
end

it "groups errors by key values" do
errors.add :attr1, 'has an error'
errors.add :attr2, 'has an error'
errors.add :attr2, 'has two errors'

expect(errors.as_json).to eq(
"attr1" => ["has an error"],
"attr2" => ["has an error", "has two errors"]
)
end
end
end

describe "#to_json" do
it "groups errors by key values" do
errors.add :attr1, 'has an error'
Expand Down

0 comments on commit a5d409d

Please sign in to comment.