Sha256: 5710fe3611d55b2d9ed76ea781cc1c9948ac16551d7b88c3510ec80e193d009c

Contents?: true

Size: 1.1 KB

Versions: 13

Compression:

Stored size: 1.1 KB

Contents

module Formulario
  class Validator

    def initialize(&validation_block)
      @validation_block = validation_block if block_given?
    end

    def call(value:, field_name: nil, object: nil)
      @value      = value
      @field_name = field_name
      @object     = object
      @valid      = object.instance_exec(value, &validation_block)
      @validated  = true

      self
    end

    def to_proc
      method(:call)
    end

    def valid?
      raise ValidationNotPerformed unless validated?

      valid
    end

    def message
      valid? ? '' : failure_text.to_s
    end

    def on_valid
      yield if valid?

      self
    end

    def on_invalid
      yield unless valid?

      self
    end

    private

    attr_reader :value
    attr_reader :field_name
    attr_reader :object

    attr_reader :valid
    attr_reader :validated
    alias :validated? :validated

    def validate(value)
      true
    end

    def validation_block
      @validation_block ||= method(:validate)
    end


    def failure_text
      'is invalid'
    end

    ValidationNotPerformed = Class.new(RuntimeError)
  end
end

Version data entries

13 entries across 13 versions & 1 rubygems

Version Path
formulario-0.1.12 lib/formulario/validator.rb
formulario-0.1.11 lib/formulario/validator.rb
formulario-0.1.10 lib/formulario/validator.rb
formulario-0.1.9 lib/formulario/validator.rb
formulario-0.1.8 lib/formulario/validator.rb
formulario-0.1.6 lib/formulario/validator.rb
formulario-0.1.5 lib/formulario/validator.rb
formulario-0.1.4 lib/formulario/validator.rb
formulario-0.1.3 lib/formulario/validator.rb
formulario-0.1.2 lib/formulario/validator.rb
formulario-0.1.1b lib/formulario/validator.rb
formulario-0.1.1 lib/formulario/validator.rb
formulario-0.1.0 lib/formulario/validator.rb