module Bluepine::Assertions

Declarative way to deal with errors

Constants

Error
KeyError
SubsetError

Public Class Methods

included(object) click to toggle source
# File lib/bluepine/assertions.rb, line 9
def self.included(object)
  object.extend(self)
end

Public Instance Methods

assert(object, *msgs) click to toggle source

Usage

Use default error message

assert valid?

Use custom error message

assert valid?, "Invalid value"

Use custom Error class

assert valid?, ValidationError, "Invalid value"
# File lib/bluepine/assertions.rb, line 26
def assert(object, *msgs)
  raises Error, msgs << "#{object.class} is not a truthy" unless object
end
assert_in(list, value, *msgs) click to toggle source

Usage

assert_in ["john", "joe"], "joe"
assert_in { amount: 1 }, :amount
# File lib/bluepine/assertions.rb, line 47
def assert_in(list, value, *msgs)
  raises KeyError, msgs << "#{value.class} - #{value} is not in the #{list.keys}" if list.respond_to?(:key?) && !list.key?(value)
  raises KeyError, msgs << "#{value.class} - #{value} is not in the #{list}" if list.kind_of?(Array) && !list.include?(value)
end
assert_kind_of(classes, object, *msgs) click to toggle source
# File lib/bluepine/assertions.rb, line 34
def assert_kind_of(classes, object, *msgs)
  classes = normalize_array(classes)
  found   = classes.find { |klass| object.kind_of?(klass) }

  raises Error, msgs << "#{object.class} must be an instance of #{classes.map(&:name).join(', ')}" unless found
end
Also aliased as: assert_kind_of_either
assert_kind_of_either(classes, object, *msgs)
Alias for: assert_kind_of
assert_not(object, *msgs) click to toggle source
# File lib/bluepine/assertions.rb, line 30
def assert_not(object, *msgs)
  raises Error, msgs << "#{object.class} is not a falsey" if object
end
assert_subset_of(parent, subset, *msgs) click to toggle source
# File lib/bluepine/assertions.rb, line 52
def assert_subset_of(parent, subset, *msgs)
  rest = subset - parent
  raises SubsetError, msgs << "#{rest} are not subset of #{parent}" if rest.present?
end

Private Instance Methods

normalize_array(values) click to toggle source
# File lib/bluepine/assertions.rb, line 59
def normalize_array(values)
  values.respond_to?(:each) ? values : [values]
end
raises(error, msgs = []) click to toggle source

allow caller to pass custom Error

# File lib/bluepine/assertions.rb, line 64
def raises(error, msgs = [])
  error, msg = msgs unless msgs.first.kind_of?(String)

  # Error class has its own error message and caller
  # doesn't specify custom message
  if msgs.length == 2
    if error.respond_to?(:message)
      msg = error.message
    elsif error.respond_to?(:new)
      msg = error.new&.message
    end
  end

  raise error, msg || msgs.last
end