Module: Insist::Predicates
Constant Summary collapse
- PREDICATE_METHOD_RE =
/\?$/
Instance Method Summary collapse
-
#is_a?(klass) ⇒ Boolean
Fails if the value.is_a?(klass) returns false.
-
#method_missing(m, *args) ⇒ Object
Pass through any ‘foo?’ style method calls to the ‘value’ and fail if the the return is false.
-
#respond_to?(method) ⇒ Boolean
Fails if the value does not respond to a method.
Methods included from Assert
Dynamic Method Handling
This class handles dynamic methods through the method_missing method
#method_missing(m, *args) ⇒ Object
Pass through any ‘foo?’ style method calls to the ‘value’ and fail if the the return is false.
25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 |
# File 'lib/insist/predicates.rb', line 25 def method_missing(m, *args) # If this is a predicate method (ends in question mark) # call it on the value and assert truthiness. if PREDICATE_METHOD_RE.match(m.to_s) insist { value }.respond_to?(m) # call the method, like .empty?, result must be truthy. result = value.send(m, *args) assert(result, "#{value.class}{#{value.inspect}}##{m}(#{args.join(",")}) " \ "expected to return a truthy value, but returned #{result}") return result else return super(m, *args) end end |
Instance Method Details
#is_a?(klass) ⇒ Boolean
Fails if the value.is_a?(klass) returns false.
insist { “hurray” }.is_a?(Number)
19 20 21 |
# File 'lib/insist/predicates.rb', line 19 def is_a?(klass) assert(value.is_a?(klass), "#{value.class} is not a #{klass}") end |
#respond_to?(method) ⇒ Boolean
Fails if the value does not respond to a method.
insist { “hurray” }.respond_to?(:size)
11 12 13 14 |
# File 'lib/insist/predicates.rb', line 11 def respond_to?(method) assert(value.respond_to?(method), "#{value.class} does not respond to the '#{method}' method") end |