Method: Object#assert!

Defined in:
lib/mini_sanity/assert.rb

#assert!(pattern = MiniSanity::TRUTHY, hint: nil) ⇒ self #assert!(pattern = MiniSanity::TRUTHY, hint: nil) {|itself| ... } ⇒ self

Checks that a given pattern matches the Object (or a derivative value), and returns the Object. Raises an exception if the pattern does not match.

If a block is given, the Object is yielded to the block, and the derivative value returned by the block is checked instead.

Examples:

Match truthy

"foo".assert!  # == "foo"
nil.assert!    # raises exception

Match expected value

"foo".assert!("foo")  # == "foo"
"bar".assert!("foo")  # raises exception

Match Set of permitted values

"foo".assert!(Set["foo", "bar"])  # == "foo"
"bar".assert!(Set["foo", "bar"])  # == "bar"
"baz".assert!(Set["foo", "bar"])  # raises exception

Match Class

25.assert!(Integer)   # == 25
2.5.assert!(Integer)  # raises exception

Match Regexp

"foo".assert!(/^f/)  # == "foo"
"bar".assert!(/^f/)  # raises exception

Match Range

2.assert!(1..4)  # == 2
5.assert!(1..4)  # raises exception

Match truthy derivative value

[2, 5].assert!(&:any?)  # == [2, 5]
[nil].assert!(&:any?)   # raises exception

Match derivative value

[2, 5].assert!(1.., &:length)  # == [2, 5]
[].assert!(1.., &:length)      # raises exception

Overloads:

  • #assert!(pattern = MiniSanity::TRUTHY, hint: nil) ⇒ self

    Parameters:

    • pattern (#===) (defaults to: MiniSanity::TRUTHY)
    • hint (String) (defaults to: nil)

      Hint to include in the error message

    Returns:

    • (self)

    Raises:

  • #assert!(pattern = MiniSanity::TRUTHY, hint: nil) {|itself| ... } ⇒ self

    Parameters:

    • pattern (#===) (defaults to: MiniSanity::TRUTHY)
    • hint (String) (defaults to: nil)

      Hint to include in the error message

    Yield Parameters:

    • itself (self)

    Yield Returns:

    • (Object)

      Derivative value

    Returns:

    • (self)

    Raises:



74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
# File 'lib/mini_sanity/assert.rb', line 74

def assert!(pattern = MiniSanity::TRUTHY, hint: nil, &block)
  result = block ? block.call(self) : self

  unless pattern === result
    raise MiniSanity::Error.new("Assert failed", {
      "Value" => self.inspect,
      "Derived value (from #{MiniSanity::Error.describe_block(&block) || "block"})" =>
        (result.inspect if block),
      "Assert matches" => pattern.inspect,
      "Hint" => hint,
    })
  end

  self
end