Module: Bluepine::Assertions

Overview

Declarative way to deal with errors

Constant Summary collapse

Error =
Class.new(StandardError)
KeyError =
Class.new(Error)
SubsetError =
Class.new(Error)

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.included(object) ⇒ Object



9
10
11
# File 'lib/bluepine/assertions.rb', line 9

def self.included(object)
  object.extend(self)
end

Instance Method Details

#assert(object, *msgs) ⇒ Object

Usage

Use default error message

assert valid?

Use custom error message

assert valid?, "Invalid value"

Use custom Error class

assert valid?, ValidationError, "Invalid value"


26
27
28
# 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) ⇒ Object

Usage

assert_in ["john", "joe"], "joe"
assert_in { amount: 1 }, :amount


47
48
49
50
# 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) ⇒ Object Also known as: assert_kind_of_either



34
35
36
37
38
39
# 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

#assert_not(object, *msgs) ⇒ Object



30
31
32
# 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) ⇒ Object



52
53
54
55
# 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