Sha256: 5d967e567270437245d7341d4e9116e35ccfccf24f2e3c8bd4229eb68fa0aee9

Contents?: true

Size: 1.76 KB

Versions: 11

Compression:

Stored size: 1.76 KB

Contents

# frozen_string_literal: true

module Parametric
  class BlockValidator
    def self.build(meth, &block)
      klass = Class.new(self)
      klass.public_send(meth, &block)
      klass
    end

    def self.message(&block)
      @message_block = block if block_given?
      @message_block if instance_variable_defined?('@message_block')
    end

    def self.validate(&validate_block)
      @validate_block = validate_block if block_given?
      @validate_block if instance_variable_defined?('@validate_block')
    end

    def self.coerce(&coerce_block)
      @coerce_block = coerce_block if block_given?
      @coerce_block
    end

    def self.eligible(&block)
      @eligible_block = block if block_given?
      @eligible_block if instance_variable_defined?('@eligible_block')
    end

    def self.meta_data(&block)
      @meta_data_block = block if block_given?
      @meta_data_block if instance_variable_defined?('@meta_data_block')
    end

    attr_reader :message

    def initialize(*args)
      @args = args
      @message = 'is invalid'
      @validate_block = self.class.validate || ->(*args) { true }
      @coerce_block = self.class.coerce || ->(v, *_) { v }
      @eligible_block = self.class.eligible || ->(*args) { true }
      @meta_data_block = self.class.meta_data || ->(*args) { {} }
    end

    def eligible?(value, key, payload)
      args = (@args + [value, key, payload])
      @eligible_block.call(*args)
    end

    def coerce(value, key, context)
      @coerce_block.call(value, key, context)
    end

    def valid?(value, key, payload)
      args = (@args + [value, key, payload])
      @message = self.class.message.call(*args) if self.class.message
      @validate_block.call(*args)
    end

    def meta_data
      @meta_data_block.call *@args
    end
  end
end

Version data entries

11 entries across 11 versions & 1 rubygems

Version Path
parametric-0.2.21 lib/parametric/block_validator.rb
parametric-0.2.20 lib/parametric/block_validator.rb
parametric-0.2.19 lib/parametric/block_validator.rb
parametric-0.2.18 lib/parametric/block_validator.rb
parametric-0.2.17 lib/parametric/block_validator.rb
parametric-0.2.16 lib/parametric/block_validator.rb
parametric-0.2.15 lib/parametric/block_validator.rb
parametric-0.2.14 lib/parametric/block_validator.rb
parametric-0.2.13 lib/parametric/block_validator.rb
parametric-0.2.12 lib/parametric/block_validator.rb
parametric-0.2.11 lib/parametric/block_validator.rb