json_errors.rb 753 B

12345678910111213141516171819202122232425262728293031323334353637
  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 =
  7. begin
  8. ActiveSupport::JSON.decode(json)['errors'] || {}
  9. rescue
  10. {}
  11. end
  12. case data
  13. when String
  14. from_string(data, save_cache)
  15. else
  16. from_hash(data, save_cache)
  17. end
  18. end
  19. def from_hash(messages, save_cache = false)
  20. clear unless save_cache
  21. messages.each do |key, errors|
  22. errors.each do |error|
  23. add(key, error)
  24. end
  25. end
  26. end
  27. def from_string(error, save_cache = false)
  28. clear unless save_cache
  29. add(:base, error)
  30. end
  31. end
  32. end