Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Make Errors render the same as ActiveModel::Errors #25

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
44 changes: 44 additions & 0 deletions spec/simple_command/errors_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,51 @@
it "returrns the full messages array" do
expect(errors.full_messages).to eq ["Attr1 has an error", "Attr2 has an error", "Attr2 has two errors"]
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'
errors.add :attr2, 'has an error'
errors.add :attr2, 'has two errors'

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