Class: SendleAPI::Errors
- Inherits:
-
ActiveModel::Errors
- Object
- ActiveModel::Errors
- SendleAPI::Errors
- Defined in:
- lib/sendle_api/errors.rb
Instance Method Summary collapse
-
#from_array(messages, save_cache = false) ⇒ Object
Grabs errors from an array of messages (like ActiveRecord::Validations).
-
#from_hash(messages, save_cache = false) ⇒ Object
Grabs errors from a hash of attribute => array of errors elements The second parameter directs the errors cache to be cleared (default) or not (by passing true).
-
#from_json(json, save_cache = false) ⇒ Object
Grabs errors from a json response.
Instance Method Details
#from_array(messages, save_cache = false) ⇒ Object
Grabs errors from an array of messages (like ActiveRecord::Validations). The second parameter directs the errors cache to be cleared (default) or not (by passing true).
10 11 12 13 14 15 16 17 18 19 20 21 |
# File 'lib/sendle_api/errors.rb', line 10 def from_array(, save_cache = false) clear unless save_cache humanized_attributes = Hash[@base.known_attributes.map { |attr_name| [attr_name.humanize, attr_name] }] .each do || = humanized_attributes.keys.sort_by { |a| -a.length }.detect do |attr_name| if [0, attr_name.size + 1] == "#{attr_name} " add humanized_attributes[attr_name], [(attr_name.size + 1)..-1] end end self[:base] << if .nil? end end |
#from_hash(messages, save_cache = false) ⇒ Object
Grabs errors from a hash of attribute => array of errors elements The second parameter directs the errors cache to be cleared (default) or not (by passing true)
Unrecognized attribute names will be humanized and added to the record’s base errors.
29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 |
# File 'lib/sendle_api/errors.rb', line 29 def from_hash(, save_cache = false) clear unless save_cache # delete top level not-needed keys .delete("error") .delete("error_description") .each do |(key, errors)| errors.each do |error| if @base.known_attributes.include?(key) add key, error elsif key == "base" self[:base] << error else # reporting an error on an attribute not in attributes # format and add them to base self[:base] << "#{key.humanize} #{error}" end end end end |
#from_json(json, save_cache = false) ⇒ Object
Grabs errors from a json response.
52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 |
# File 'lib/sendle_api/errors.rb', line 52 def from_json(json, save_cache = false) decoded = ActiveSupport::JSON.decode(json) || {} rescue {} if decoded.kind_of?(Hash) && (decoded.has_key?("errors") || decoded.empty?) errors = decoded["errors"] || {} if errors.kind_of?(Array) # 3.2.1-style with array of strings ActiveSupport::Deprecation.warn("Returning errors as an array of strings is deprecated.") from_array errors, save_cache else # 3.2.2+ style from_hash errors, save_cache end else # <3.2-style respond_with - lacks 'errors' key ActiveSupport::Deprecation.warn('Returning errors as a hash without a root "errors" key is deprecated.') from_hash decoded, save_cache end end |