Sha256: c3ca6c0ab83a818beaab32218c4bc303b4c1e3d783776435506a3e08844849c1

Contents?: true

Size: 1.33 KB

Versions: 13

Compression:

Stored size: 1.33 KB

Contents

module MotionPrime
  class Errors
    attr_accessor :_unique_keys

    def initialize(model)
      @_unique_keys = []
      @model = model
      model.class.attributes.map(&:to_sym).each do |key|
        initialize_for_key key
      end
    end

    def unique_key(key)
      [key, @model.object_id].join('_').to_sym
    end

    def initialize_for_key(key)
      unique_key = unique_key(key)

      return if @_unique_keys.include?(unique_key)
      @_unique_keys << unique_key
      instance_variable_set("@#{unique_key}", [])
      self.class.send :attr_accessor, unique_key
    end

    def get(key)
      initialize_for_key(key)
      send(unique_key(key))
    end

    def set(key, errors)
      initialize_for_key(key)
      send :"#{unique_key(key)}=", Array.wrap(errors)
    end

    def add(key, error)
      send(unique_key(key)) << error
    end

    def [](key)
      get(key)
    end

    def []=(key, errors)
      set(key, errors)
    end

    def reset_for(key)
      send :"#{unique_key(key)}=", []
    end

    def reset
      @_unique_keys.each do |unique_key|
        send :"#{unique_key}=", []
      end
    end

    def messages
      @_unique_keys.map{ |uniq_k| send(uniq_k) }.compact.flatten
    end

    def blank?
      messages.blank?
    end

    def present?
      !blank?
    end

    def to_s
      messages.join(';')
    end
  end
end

Version data entries

13 entries across 13 versions & 1 rubygems

Version Path
motion-prime-0.5.2 motion-prime/models/errors.rb
motion-prime-0.5.1 motion-prime/models/errors.rb
motion-prime-0.5.0 motion-prime/models/errors.rb
motion-prime-0.4.5 motion-prime/models/errors.rb
motion-prime-0.4.4 motion-prime/models/errors.rb
motion-prime-0.4.3 motion-prime/models/errors.rb
motion-prime-0.4.2 motion-prime/models/errors.rb
motion-prime-0.4.1 motion-prime/models/errors.rb
motion-prime-0.4.0 motion-prime/models/errors.rb
motion-prime-0.3.3 motion-prime/models/errors.rb
motion-prime-0.3.2 motion-prime/models/errors.rb
motion-prime-0.3.1 motion-prime/models/errors.rb
motion-prime-0.3.0 motion-prime/models/errors.rb