Make Errors render the same as ActiveModel::Errors#25
Open
bmorrall wants to merge 2 commits intonebulab:masterfrom
Open
Make Errors render the same as ActiveModel::Errors#25bmorrall wants to merge 2 commits intonebulab:masterfrom
bmorrall wants to merge 2 commits intonebulab:masterfrom
Conversation
b875686 to
ef44d26
Compare
ef44d26 to
a5d409d
Compare
|
Looking in active_model/serializers/json.rb there's a def as_json(options = nil)
root = if options && options.key?(:root)
options[:root]
else
true
# could be modified to use an initializer var,
# like active record has ActiveRecord::Base.include_root_in_json = true
end
json = 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)
if root
root = :errors if root == true
{ root => json }
else
json
end
endwith root being a boolean value or a string to be the key of the generated json |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
I looked into Issue #24 to determine why the Errors object was behaving differently from "ActiveSupport::Errors".
From what I've found, Rails will render the Errors using
Hash#as_jsonas implemented by ActiveSupport, instead ofHash#to_jsonas included with base Ruby.I wrote a work around that will provide an
as_jsonmethod whenHash#as_jsonhas been provided by ActiveSupport (i.e. every Rails project), and will raise an error when it is not provided.I also included some test coverage to ensure to_json works as expected, to avoid any regressions.