Module: Demand

Extended by:
Demand
Included in:
Demand
Defined in:
lib/demand.rb,
lib/demand/version.rb

Overview

require ‘pry’

Constant Summary collapse

VERSION =
"1.0.0"

Instance Method Summary collapse

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).

Parameters:

  • var

    The variable you wish to check.

  • default (defaults to: nil)

    The return value you want if the check fails.

  • type (Class, Module) (defaults to: nil)

    Variable must be of this class or include this module for the check to pass. The module ‘Boolean’ can be used, to mean the value must be true or false.

Yields:

  • (var)

    If a block is given and the check passes, the original variable is also yielded to the block.

Returns:

  • The original variable if the check passes. Otherwise, the default value is returned.



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