Module: Enumerable

Defined in:
lib/mini_sanity/enumerable.rb,
lib/mini_sanity/util/enumerable.rb

Instance Method Summary collapse

Instance Method Details

#assert_empty!(name = nil) ⇒ self

Checks that the Enumerable is empty, and returns the Enumerable unmodified. If the Enumerable fails this check, an exception is raised.

Examples:

errors = []
errors.assert_empty!  # == []

errors = ["something went wrong"]
errors.assert_empty!  # raises exception

Parameters:

  • name (String, Symbol) (defaults to: nil)

    optional name to include in the error message

Returns:

  • (self)

Raises:



19
20
21
22
23
24
25
26
# File 'lib/mini_sanity/enumerable.rb', line 19

def assert_empty!(name = nil)
  if self.any?{ true }
    raise MiniSanity::Error.new(name,
      "empty #{self.class}",
      self.inspect)
  end
  self
end

#first!(n = nil) ⇒ Object, Array

Like Enumerable#first, but raises an exception if the Enumerable does not contain the requested number of elements.

Examples:

[7, 8, 9].first     # == 7
[7, 8, 9].first(1)  # == [7]
[7, 8, 9].first(2)  # == [7, 8]
[7, 8, 9].first(4)  # raises exception
[].first            # raises exception

Parameters:

  • n (Integer) (defaults to: nil)

    requested number of elements

Returns:

Raises:

  • (MiniSanity::Error)

    if the Enumerable does not contain the requested number of elements



19
20
21
22
23
24
25
26
27
28
29
# File 'lib/mini_sanity/util/enumerable.rb', line 19

def first!(n = nil)
  result = n.nil? ? self.first : self.first(n)

  if (result.nil? && !self.any?{ true }) || (!n.nil? && result.length < n)
    raise MiniSanity::Error.new(nil,
      "Enumerable having at least #{n || 1} elements",
      self.inspect)
  end

  result
end

#refute_empty!(name = nil) ⇒ self

Checks that the Enumerable is not empty, and returns the Enumerable unmodified. If the Enumerable fails this check, an exception is raised.

Examples:

["result 1"].refute_empty!  # == ["result 1"]
[].refute_empty!            # raises exception

Parameters:

  • name (String, Symbol) (defaults to: nil)

    optional name to include in the error message

Returns:

  • (self)

Raises:



41
42
43
44
45
46
47
48
49
50
# File 'lib/mini_sanity/enumerable.rb', line 41

def refute_empty!(name = nil)
  # NOTE use #any? instead of #none? because Array#none? seems to be
  # significantly slower than Array#any? (and likewise for Hash)
  if !self.any?{ true }
    raise MiniSanity::Error.new(name,
      "non-empty #{self.class}",
      self.inspect)
  end
  self
end