Sha256: d2cb061f42ce8712cf42ac70befa3e0052d0e449ea6d7eaa01b1593a3fc1da33

Contents?: true

Size: 1.25 KB

Versions: 3

Compression:

Stored size: 1.25 KB

Contents

module ActiveResource # :nodoc: all
  module Validations
    # Loads the set of remote errors into the object's Errors based on the
    # content-type of the error-block received.
    def load_remote_errors(remote_errors, save_cache = false) #:nodoc:
      if self.class.format == ActiveResource::Formats::JsonAPIFormat
        errors.from_json_api(remote_errors.response.body, save_cache)
      elsif self.class.format == ActiveResource::Formats[:json]
        super
      end
    end
  end

  class Errors
    def from_json_api(json, save_cache = false)
      raw_errors = decoded_errors(json)
      errors = meta_errors(raw_errors)
      if errors.present?
        from_hash errors, save_cache
      else
        from_array raw_errors.map { |e| e['title'] }
      end
    end

    private

    def decoded_errors(json)
      Array((Hash(ActiveSupport::JSON.decode(json)))['errors'])
    rescue
      []
    end

    def meta_errors(raw_errors)
      {}.tap do |errors|
        raw_errors.each do |error|
          next unless error['meta']
          error['meta'].map do |attr, message|
            friendly_attr = attr.tr('.', ' ')
            errors[friendly_attr] ||= []
            errors[friendly_attr] << message
          end
        end
      end
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
esp_sdk-2.5.0 lib/esp/extensions/active_resource/validations.rb
esp_sdk-2.4.0 lib/esp/extensions/active_resource/validations.rb
esp_sdk-2.3.0 lib/esp/extensions/active_resource/validations.rb