Module: Stannum::ParameterValidation

Defined in:
lib/stannum/parameter_validation.rb

Overview

Provides a DSL for validating method parameters.

Use the .validate_parameters method to define parameter validation for an instance method of the class or module.

Ruby does not distinguish between an explicit nil versus an undefined value in an Array or Hash, but does distinguish between a nil value and a missing parameter. Be careful when validating methods with optional or default arguments or keywords:

  • If the actual value can be nil, or if the default parameter is nil, then use the optional: true option. This will match an empty arguments list, or an arguments list with nil as the first value:

    def method_with_optional_argument(name: nil)
      @name = name || 'Alan Bradley'
    end
    
    validate_parameters(:method_with_optional_argument) do
      argument :name, optional: true
    end
    
  • If the default parameter is any other value, then use the default: true option. This will match an empty arguments list, but not an arguments list with nil as the first value:

    def method_with_default_argument(role: 'User')
      @role = role
    end
    
    validate_parameters(:method_with_default_argument) do
      argument :role, default: true
    end
    

Examples:

Validating Parameters

class PerformAction
  include Stannum::ParameterValidation

  def perform(action, record_class = nil, user:, role: 'User')
  end

  validate_parameters(:perform) do
    argument :action,       Symbol
    argument :record_class, Class,  optional: true
    keyword  :role,         String, default:  true
    keyword  :user,         Stannum::Constraints::Type.new(User)
  end
end

Validating Class Methods

module Authorization
  extend Stannum::ParameterValidation

  class << self
    def authorize_user(user, role: 'User')
    end

    validate_parameters(:authorize_user) do
      argument :user, User
      argument :role, String, default: true
    end
  end
end

See Also:

Defined Under Namespace

Modules: ClassMethods Classes: MethodValidations

Constant Summary collapse

VALIDATION_SUCCESS =

This constant is part of a private API. You should avoid using this constant if possible, as it may be removed or be changed in the future.

Value used to indicate a successful validation of the parameters.

Object.new.freeze

Class Method Summary collapse

Class Method Details

.add_method_validations(other) ⇒ Object



160
161
162
163
164
165
166
167
# File 'lib/stannum/parameter_validation.rb', line 160

def add_method_validations(other)
  other.extend(ClassMethods)

  validations = MethodValidations.new

  other.const_set(:MethodValidations, validations)
  other.prepend(validations)
end