Sha256: cf0fdf0534357f3c886d31494792a02a1409cb55f0021e4868b6b52c32c60148

Contents?: true

Size: 988 Bytes

Versions: 1

Compression:

Stored size: 988 Bytes

Contents

require 'ostruct'

module Tidylib
  class ValidationErrors
    include Enumerable

    VERSION = "0.1.1"

    def initialize
      @errors = []
    end

    def empty?
      @errors.empty?
    end

    def add(topic, message, context={})
      error = OpenStruct.new(
        topic: topic,
        message: message,
        context: context
      )

      @errors << error
    end

    def [](topic)
      @errors.select do |error|
        error.topic == topic
      end.map do |error|
        [ error.message, error.context ]
      end
    end
    alias :on :[]

    def each(&blk)
      @errors.each do |error|
        yield error.topic, error.message, error.context
      end
    end

    def grouped_by_topic
      @errors.inject({}) do |grouped, error|
        grouped[error.topic] ||= []
        grouped[error.topic] << [error.message, error.context]

        grouped
      end
    end

    def clear
      @errors = []
    end

    def count
      @errors.length
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
tidylib-validation_errors-0.1.1 lib/tidylib/validation_errors.rb