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

Conversation

bmorrall
Copy link
Contributor

@bmorrall bmorrall commented Mar 1, 2020

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_json as implemented by ActiveSupport, instead of Hash#to_json as included with base Ruby.

I wrote a work around that will provide an as_json method when Hash#as_json has 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.

@bmorrall bmorrall changed the title Add test coverage for Errors#to_json Make Errors render the same as ActiveModel::Errors Mar 2, 2020
@thlmenezes
Copy link

Looking in active_model/serializers/json.rb there's a root options that I think it could be useful here, because of the recurring pattern of wrapping the json results in a errors key; so the code could be modified to something like

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
end

with root being a boolean value or a string to be the key of the generated json

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants