Module ParameterValidator
In: lib/parmvalid.rb

ParameterValidator is a mixin module providing parameter validation for functions and methods that employ Ruby‘s "keyword arguments" implemention.

To use it in a class:

  • require ‘parmvalid‘
  • include ParameterValidator
  • in your method definition, invoke ParameterValidator#validate_parameters, passing in the hash of the actual parameters, and a hash of valid parameters ( name=>default_value pairs, with default_value==REQUIRED if the parameter is not optional). The return value from validate_parameters will be a hash of the parameters, both the optional ones that weren‘t passed in, and the ones that were.
  • if you want each parameter validated and then set as an instance variable of the class, use validate_and_instantiate_parameters.
  • if you want each parameter validated and then set using similarly-named setters in the class, use validate_and_set_parameters.

Example:

  require 'parmvalid'

  class Demo
    include ParameterValidator

    def initialize( args )
      validate_and_instantiate_parameters( args,
        { :name=>REQUIRED, :date=>Time.now, :location=nil, :memo=>REQUIRED } )

      p @name
      p @date
      p @location
      p @memo
    end
  end

  d = Demo.new( :name=>"Jamis", :memo=>"Some memo" )

Author: Jamis Buck (jgb3@email.byu.edu)

Methods

Classes and Modules

Class ParameterValidator::InvalidParameterException
Class ParameterValidator::MissingParameterException

Constants

REQUIRED = Object.new   A unique constant, used as the default value for a parameter to indicate that it is required.

Public Instance methods

For each key in the given hash, create an identically-named instance variable and set its value to the value of the given key.

For each key in the given hash, assign its value to an identically-named setter in the current class.

Validate and instantiate the given parameters by calling both validate_parameters and instantiate_parameters. Return the hash of all parameters.

Validate and set the given parameters by calling both validate_parameters and set_parameters. Return the hash of all parameters.

Validates a hash of actual parameters (as created by Ruby‘s pseudo-"keyword arguments" feature) against a list of valid parameters.

Parameters:

  • actual_parms: the hash of actual parameters that were given by Ruby‘s pseudo-"keyword arguments" feature.
  • valid_parameters: the hash of valid parameters, where the key for each entry in the hash is a symbol naming the acceptable parameter, and the value is the default value for that parameter. If the default value for any entry is the constant REQUIRED, then the parameter must not be absent from the actual_parms hash.

Returns: a hash of all parameters, together with either the actual value that was passed in, or (in the case of optional parameters that were not passed in) the default value.

[Validate]