Sha256: ab11162945a1725866c865a299005bb06e6ffb759052f06580ad3cc3979a095f

Contents?: true

Size: 1.39 KB

Versions: 1

Compression:

Stored size: 1.39 KB

Contents

require 'rom/rails/model/validator/uniqueness_validator'

module ROM
  module Model
    # Mixin for ROM-compliant validator objects
    #
    # @example
    #
    #
    #   class UserParams
    #     include ROM::Model::Params
    #
    #     attribute :name
    #
    #     validates :name, presence: true
    #   end
    #
    #   class UserValidator
    #     include ROM::Model::Validator
    #   end
    #
    #   params = UserParams.new(name: '')
    #   UserValidator.call(params) # raises ValidationError
    #
    # @api public
    module Validator
      def self.included(base)
        base.class_eval do
          extend ClassMethods
          include ActiveModel::Validations
          include Equalizer.new(:params, :errors)
        end
      end

      attr_reader :params
      delegate :model_name, to: :params

      def initialize(params)
        @params = params
      end

      def to_model
        params
      end

      def call
        raise ValidationError, errors unless valid?
        params
      end

      private

      def method_missing(name)
        params[name]
      end

      module ClassMethods
        def relation(name = nil)
          @relation = name if name
          @relation
        end

        def model_name
          params.model_name
        end

        def call(params)
          validator = new(params)
          validator.call
        end
      end
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
rom-rails-0.3.0.beta1 lib/rom/rails/model/validator.rb