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 StepError object (through StepError#step) and for instance use it to customize error reporting.

The :message property will override the default error message produced by StepError#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.



792
793
794
795
# File 'lib/ippon/validate.rb', line 792

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.



789
790
791
# File 'lib/ippon/validate.rb', line 789

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.



803
804
805
# File 'lib/ippon/validate.rb', line 803

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

#process(result) ⇒ Object

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



818
819
820
# File 'lib/ippon/validate.rb', line 818

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.



813
814
815
# File 'lib/ippon/validate.rb', line 813

def type
  @props[:type]
end