json_errors.rb 698 B

1234567891011121314151617181920212223242526272829303132
  1. # frozen_string_literal: true
  2. require 'active_resource/base'
  3. module ActiveResource
  4. class Errors < ActiveModel::Errors
  5. def from_json(json, save_cache = false)
  6. data = ActiveSupport::JSON.decode(json)['errors'] || {} rescue {}
  7. case data
  8. when String
  9. from_string(data, save_cache)
  10. else
  11. from_hash(data, save_cache)
  12. end
  13. end
  14. def from_hash(messages, save_cache = false)
  15. clear unless save_cache
  16. messages.each do |key,errors|
  17. errors.each do |error|
  18. add(key, error)
  19. end
  20. end
  21. end
  22. def from_string(error, save_cache = false)
  23. clear unless save_cache
  24. add(:base, error)
  25. end
  26. end
  27. end