Module: FailFast::Assertions

Defined in:
lib/fail_fast.rb

Instance Method Summary collapse

Instance Method Details

#assert(*values, &block) ⇒ Object

Assert that no values are nil or false. Returns the last value.



13
14
15
16
17
# File 'lib/fail_fast.rb', line 13

def assert(*values, &block)
  iterate_and_return_last(values, block) do |v|
    raise_assertion_error unless v
  end
end

#assert_exists(*values, &block) ⇒ Object

Assert that no values are nil. Returns the last value.



27
28
29
# File 'lib/fail_fast.rb', line 27

def assert_exists(*values, &block)
  iterate_and_return_last(values, block) {  |value| deny(value.nil?) }
end

#assert_keys(hash, *keys) ⇒ Object

Assert that hash exists, responds to #[], and contains a non-nil value for all keys. Returns hash.



43
44
45
46
47
48
49
# File 'lib/fail_fast.rb', line 43

def assert_keys(hash, *keys)
  assert_exists(hash)
  assert(hash.respond_to?(:[]))
  values = keys.inject([]) { |vals, k| vals << assert_exists(hash[k]) }
  assert(yield(*values)) if block_given?
  hash
end

#assert_one_or_more(*values, &block) ⇒ Object

Assert that values are collections that contain at least one element. Returns the last value.



33
34
35
36
37
38
39
# File 'lib/fail_fast.rb', line 33

def assert_one_or_more(*values, &block)
  iterate_and_return_last(values, block) do |value|
    assert_exists(value)
    deny(value.kind_of?(String))
    deny(value.empty?)
  end
end

#assert_only_keys(hash, *keys) ⇒ Object

Assert that hash exists, responds to #[], and has no keys other than keys. Returns hash.



53
54
55
56
57
58
59
60
61
# File 'lib/fail_fast.rb', line 53

def assert_only_keys(hash, *keys)
  assert_exists(hash)
  assert(hash.respond_to?(:[]))
  values = hash.inject([]) { |vals, (k, v)| 
    assert(keys.include?(k)); vals << hash[k] 
  }
  assert(yield(*values)) if block_given?
  hash
end

#assert_respond_to(object, *messages) ⇒ Object

Assert that object responds to messages. Returns object.



64
65
66
67
68
69
70
# File 'lib/fail_fast.rb', line 64

def assert_respond_to(object, *messages)
  messages.each do |message|
    assert(object.respond_to?(message))
  end
  assert(yield(object)) if block_given?
  object
end

#deny(*values) ⇒ Object

The opposite of #assert.



20
21
22
23
24
# File 'lib/fail_fast.rb', line 20

def deny(*values)
  assert(*values.map{ |v| !v})
  assert(yield(*values)) if block_given?
  values.last
end