Class: Ippon::Validate::Step

Inherits:
Schema
  • Object
show all
Defined in:
lib/ippon/validate.rb

Overview

Step is the common class for all schemas that does actual validation and transformation on the value (as opposed to just combining other schemas).

Every Step class take a props Hash in their constructor and you are free to store arbitrary data here. You can later access this data from the Error object (through Error#step) and for instance use it to customize error reporting.

The :message property will override the default error message produced by Error#message and #message.

Examples:

How to access custom properties from the error object

module Schemas
  extend Ippon::Validate::Builder

  Even = trim |
    required |
    number(custom: 123) |
    validate(message: "must be even") { |v| v % 2 == 0 }

end

result = Schemas::Even.validate(" 1a1")
result.errors[0].step.class           # => Ippon::Validate::Step
result.errors[0].step.props[:type]    # => :number
result.errors[0].step.props[:custom]  # => 123

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods inherited from Schema

#&, #unhalt, #validate, #validate!, #|

Constructor Details

#initialize(props = {}, &processor) ⇒ Step

Returns a new instance of Step.

Parameters:

  • props (Hash) (defaults to: {})

    properties for this step.


702
703
704
705
# File 'lib/ippon/validate.rb', line 702

def initialize(props = {}, &processor)
  @props = props.freeze
  @processor = processor
end

Instance Attribute Details

#propsHash (readonly)

Returns properties for this step.

Returns:

  • (Hash)

    properties for this step.


699
700
701
# File 'lib/ippon/validate.rb', line 699

def props
  @props
end

Instance Method Details

#messageString

The error message for this step.

This will return the :message property, failing back to “must be valid” if it's missing.

Returns:

  • (String)

    The error message.


713
714
715
# File 'lib/ippon/validate.rb', line 713

def message
  @props.fetch(:message, "must be valid")
end

#process(result) ⇒ Object

Implements the Ippon::Validate::Schema#process interface.


728
729
730
# File 'lib/ippon/validate.rb', line 728

def process(result)
  @processor.call(result)
end

#typeString?

The type of this step.

This will return the :type property, failing back to nil if it's missing.

Returns:

  • (String, nil)

    The error message.


723
724
725
# File 'lib/ippon/validate.rb', line 723

def type
  @props[:type]
end