Module: Demand
Overview
require ‘pry’
Constant Summary collapse
- VERSION =
"1.0.0"
Instance Method Summary collapse
-
#demand(var, default = nil, type = nil) {|var| ... } ⇒ Object
Checks if a passed variable is present and as expected.
Instance Method Details
#demand(var, default = nil, type = nil) {|var| ... } ⇒ Object
Note:
If you want the check to pass just if the variable is nil, specify type = NilClass
Checks if a passed variable is present and as expected. If so, returns and optionally yields it. Otherwise, a default is returned. The check will fail for empty arrays, hashes and strings (including whitespace strings).
22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 |
# File 'lib/demand.rb', line 22 def demand(var, default = nil, type = nil) # If type specified, must either be a class or module # Otherwise, get the class of whatever was passed if (type != nil) if (type.is_a?(Class) || type.is_a?(Module)) t = type else t = type.class end end # Check the var begin # Edge case - you want the variable to be of type NilClass if var == nil unless t == NilClass return default end # Is the variable blank? - not including false elsif !(var.present? || var == false) # Override false == blank return default # Variable is not blank # Do we need to check its class too? elsif (t != nil) unless var.is_a?(t) return default end end rescue return default end # All checks have passed by this point yield(var) if block_given? # Original variable returned return var end |