Class: Util::Args

Inherits:
Object
  • Object
show all
Defined in:
lib/util/args.rb

Overview

Functions to typecheck the arguments of a function.

Constant Summary collapse

DEFAULT_VALUES =

If no alternative value is provided to check, these will be used.

{
  Array => [],
  'Boolean' => false,
  Class => NilClass,
  Complex => 0.to_c,
  Encoding => Encoding::UTF_8,
  FalseClass => true,
  Float => 0.0,
  Hash => {},
  Integer => 0,
  Module => Kernel,
  NilClass => nil,
  Object => Object.new,
  Queue => Queue.new,
  Random => Random::DEFAULT,
  Range => (0..),
  Rational => 0.to_r,
  Regexp => /.*/,
  SizedQueue => SizedQueue.new(1),
  String => '',
  Symbol => :nil,
  Time => Time.now,
  TrueClass => false,
}
FUNCTIONS =

Do not document:

{
  Array => :to_a,
  Complex => :to_c,
  Enumerator => :to_enum,
  Float => :to_f,
  Hash => :to_h,
  Integer => :to_i,
  Rational => :to_r,
  String => :to_s,
  Symbol => :to_sym,
}

Class Method Summary collapse

Class Method Details

.check(*args) ⇒ Object+

Verify whether a given argument or arguments belong to a class or can be converted into that class. Any number of sequences of the three arguments below can be passed.

Examples:

def create_integer_hash key, value
  key, value = Util::Args.check key, Symbol, :def, value, Integer, nil
  { key => value }
end

hash1 = create_integer_hash 'hello', 13.4 # { :hello => 13 }
hash2 = create_integer_hash nil, nil # { :def => nil }

Parameters:

  • value (Object)

    argument to check

  • klass (Class, String)

    class to which it must belong; Boolean is a synonym for TrueClass; all standard classes who have #to_X will try to convert the value if it responds to the given conversion method (if not provided, NilClass is used)

  • alt (Object)

    value to use if the argument does not belong to the wanted class (if not provided, will default to DEFAULT_VALUES[klass])

Returns:

  • (Object, Array<Object>)

    an array of the checked and converted values, or just the value if the array has only one element



65
66
67
# File 'lib/util/args.rb', line 65

def self.check *args
  check_internal nil, *args
end

.check_opts(opts, *args) ⇒ Object+

Note:

It is not necessary to check whether opts is a Hash, the method will do it.

Typecheck the content of an options hash, while ignoring undefined options. Calls Args.check on the values associated with a given key, according to the rest of the informations given.

Examples:

def initialize opts={}
  @encoding, @font_size, @line_height = Util::Args.check_opts opts, \
    :enc, String, 'UTF-8', :size, Integer, 12, :height, Float, 1.0
end

Parameters:

  • opts (Hash)

    hash whose content to check

  • args (Array)

    see check for the rest of the arguments

Returns:

  • (Object, Array<Object>)

    an array of the checked and converted values, or just the value if the array has only one element



82
83
84
# File 'lib/util/args.rb', line 82

def self.check_opts opts, *args
  check_internal opts, *args
end