Class: Arg
- Inherits:
-
Object
- Object
- Arg
- Defined in:
- lib/util/arg.rb
Overview
WARNING!! The API of the module will most probably change in future versions of the gem. For now consider it for internal use only.
Functions to typecheck the arguments of a function.
Class Method Summary collapse
-
.check(value, klass, alt, disallow_nil = false) ⇒ Object
Verify whether a given argument belongs to a class or can be converted into that class.
-
.check_a(array) ⇒ Array<Object>
Easier way to typecheck a whole list of argument than individually calling Arg.check on each of them.
-
.check_h(hash, array) ⇒ Array<Object>
Typecheck the content of an options hash, while ignoring undefined options.
Class Method Details
.check(value, klass, alt, disallow_nil = false) ⇒ Object
Verify whether a given argument belongs to a class or can be converted into that class.
30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 |
# File 'lib/util/arg.rb', line 30 def self.check value, klass, alt, disallow_nil = false return alt if disallow_nil and value.nil? case klass.to_s when 'Array' then return value.respond_to?(:to_a) ? value.to_a : alt when 'Boolean' then return value === true ? true : alt when 'Complex' then return value.respond_to?(:to_c) ? value.to_c : alt when 'FalseClass' then return value === false ? false : alt when 'Float' then return value.respond_to?(:to_f) ? value.to_f : alt when 'Hash' then return value.respond_to?(:to_h) ? value.to_h : alt when 'Integer' then return value.respond_to?(:to_i) ? value.to_i : alt when 'Rational' then return value.respond_to?(:to_r) ? value.to_r : alt when 'String' then return value.respond_to?(:to_s) ? value.to_s : alt when 'Symbol' then return value.respond_to?(:to_sym) ? value.to_sym : alt when 'TrueClass' then return value === true ? true : alt else return value.is_a?(klass) ? value : alt end end |
.check_a(array) ⇒ Array<Object>
Easier way to typecheck a whole list of argument than individually calling Arg.check on each of them. Takes an array of arrays containing the three or four argument of Arg.check, performs said method on each of them, and returns an array of the results.
60 61 62 63 64 65 66 67 |
# File 'lib/util/arg.rb', line 60 def self.check_a array result = [] array.each do |elem| value, klass, alt, dis = elem result << check(value, klass, alt, (dis.nil? ? false : dis)) end result end |
.check_h(hash, array) ⇒ Array<Object>
Typecheck the content of an options hash, while ignoring undefined options. Calls Arg.check on the values associated with a given key, according to the rest of the informations given.
82 83 84 85 86 87 88 89 |
# File 'lib/util/arg.rb', line 82 def self.check_h hash, array result = [] array.each do |elem| idx, klass, alt, dis = elem result << check(hash[idx], klass, alt, (dis.nil? ? false : dis)) end result end |