Sha256: 2529799f6a4f528ea87ce2731b857e7c567ca20f7a959670ae2e14799458bb43

Contents?: true

Size: 1.86 KB

Versions: 49

Compression:

Stored size: 1.86 KB

Contents

# Like ActiveModel::Errors
class LHS::Errors
  include Enumerable

  attr_reader :messages, :message, :raw

  def initialize(response)
    @messages = messages_from_response(response)
    @message = message_from_response(response)
    @raw = response.body
  rescue JSON::ParserError # rubocop:disable Lint/HandleExceptions
  end

  def include?(attribute)
    messages[attribute].present?
  end
  alias has_key? include?
  alias key? include?

  def get(key)
    messages[key]
  end

  def set(key, value)
    messages[key] = value
  end

  delegate :delete, to: :messages

  def [](attribute)
    get(attribute.to_sym) || set(attribute.to_sym, [])
  end

  def []=(attribute, error)
    self[attribute] << error
  end

  def each
    messages.each_key do |attribute|
      self[attribute].each { |error| yield attribute, error }
    end
  end

  def size
    values.flatten.size
  end

  delegate :values, to: :messages

  delegate :keys, to: :messages

  def count
    to_a.size
  end

  def empty?
    all? { |_k, v| v && v.empty? && !v.is_a?(String) }
  end

  private

  def add_error(messages, key, value)
    messages[key] ||= []
    messages[key].push(value)
  end

  def parse_messages(json)
    messages = {}
    if json['fields']
      json['fields'].each do |field|
        field['details'].each do |detail|
          add_error(messages, field['name'].to_sym, detail['code'])
        end
      end
    end
    if json['field_errors']
      json['field_errors'].each do |field_error|
        add_error(messages, field_error['path'].join('.').to_sym, field_error['code'])
      end
    end
    messages
  end

  def messages_from_response(response)
    return {} if !response.body.is_a?(String) || response.body.length.zero?
    json = JSON.parse(response.body)
    parse_messages(json)
  end

  def message_from_response(response)
    json = JSON.parse(response.body)
    json['message']
  end
end

Version data entries

49 entries across 49 versions & 1 rubygems

Version Path
lhs-6.5.0 lib/lhs/errors.rb
lhs-6.4.0 lib/lhs/errors.rb
lhs-6.3.1 lib/lhs/errors.rb
lhs-6.3.0 lib/lhs/errors.rb
lhs-6.2.0 lib/lhs/errors.rb
lhs-6.1.0 lib/lhs/errors.rb
lhs-6.0.0 lib/lhs/errors.rb
lhs-5.7.1 lib/lhs/errors.rb
lhs-5.7.0 lib/lhs/errors.rb
lhs-5.6.6 lib/lhs/errors.rb
lhs-5.6.5 lib/lhs/errors.rb
lhs-5.6.4 lib/lhs/errors.rb
lhs-5.6.3 lib/lhs/errors.rb
lhs-5.6.2 lib/lhs/errors.rb
lhs-5.6.1 lib/lhs/errors.rb
lhs-5.6.0 lib/lhs/errors.rb
lhs-5.5.0 lib/lhs/errors.rb
lhs-5.4.2 lib/lhs/errors.rb
lhs-5.4.1 lib/lhs/errors.rb
lhs-5.4.0 lib/lhs/errors.rb