Sha256: ee2408cb076bebd2b01680369ae42b81ed32f9e493bb7abbde5f3fe2312e64d7

Contents?: true

Size: 1.97 KB

Versions: 9

Compression:

Stored size: 1.97 KB

Contents

require 'active_model/validator'

module ROM
  module Model
    module Validator
      # Uniqueness validation
      #
      # @api public
      class UniquenessValidator < ActiveModel::EachValidator
        # Relation validator class
        #
        # @api private
        attr_reader :klass

        # error message
        #
        # @return [String, Symbol]
        #
        # @api private
        attr_reader :message

        # @api private
        def initialize(options)
          super
          @klass = options.fetch(:class)
          @message = options.fetch(:message) { :taken }
          @scope_keys = options[:scope]
        end

        # Hook called by ActiveModel internally
        #
        # @api private
        def validate_each(validator, name, value)
          scope = Array(@scope_keys).each_with_object({}) do |key, scope|
            scope[key] = validator.to_model[key]
          end
          validator.errors.add(name, message) unless unique?(name, value, scope)
        end

        private

        # Get relation object from the rom env
        #
        # @api private
        def relation
          if relation_name
            rom.relations[relation_name]
          else
            raise "relation must be specified to use uniqueness validation"
          end
        end

        # Relation name defined on the validator class
        #
        # @api private
        def relation_name
          klass.relation
        end

        # Shortcut to access global rom env
        #
        # @return [ROM::Env]
        #
        # @api private
        def rom
          ROM.env
        end

        # Ask relation if a given attribute value is unique
        #
        # This uses `Relation#unique?` interface that not all adapters can
        # implement.
        #
        # @return [TrueClass,FalseClass]
        #
        # @api private
        def unique?(name, value, scope)
          relation.unique?({name => value}.merge(scope))
        end
      end
    end
  end
end

Version data entries

9 entries across 9 versions & 2 rubygems

Version Path
rom-model-0.5.0 lib/rom/model/validator/uniqueness_validator.rb
rom-model-0.4.0 lib/rom/model/validator/uniqueness_validator.rb
rom-model-0.3.0 lib/rom/model/validator/uniqueness_validator.rb
rom-model-0.2.0 lib/rom/model/validator/uniqueness_validator.rb
rom-model-0.2.0.rc1 lib/rom/model/validator/uniqueness_validator.rb
rom-model-0.2.0.beta1 lib/rom/model/validator/uniqueness_validator.rb
rom-model-0.1.1 lib/rom/model/validator/uniqueness_validator.rb
rom-model-0.1.0 lib/rom/model/validator/uniqueness_validator.rb
rom-rails-0.5.0.beta1 lib/rom/rails/model/validator/uniqueness_validator.rb