Class: Contracts::Invariants::Invariant

Inherits:
Object
  • Object
show all
Defined in:
lib/contracts/invariants.rb

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(klass, name, &condition) ⇒ Invariant

Returns a new instance of Invariant.


40
41
42
# File 'lib/contracts/invariants.rb', line 40

def initialize(klass, name, &condition)
  @klass, @name, @condition = klass, name, condition
end

Class Method Details

.failure_callback(data) ⇒ Object


59
60
61
# File 'lib/contracts/invariants.rb', line 59

def self.failure_callback(data)
  fail InvariantError, failure_msg(data)
end

.failure_msg(data) ⇒ Object


63
64
65
66
67
68
69
# File 'lib/contracts/invariants.rb', line 63

def self.failure_msg(data)
  %{Invariant violation:
      Expected: #{data[:expected]}
      Actual: #{data[:actual]}
      Value guarded in: #{data[:target].class}::#{Support.method_name(data[:method])}
      At: #{Support.method_position(data[:method])}}
end

Instance Method Details

#check_on(target, method) ⇒ Object


48
49
50
51
52
53
54
55
56
57
# File 'lib/contracts/invariants.rb', line 48

def check_on(target, method)
  return if target.instance_eval(&@condition)

  self.class.failure_callback({
    expected: expected,
    actual:   false,
    target:   target,
    method:   method,
  })
end

#expectedObject


44
45
46
# File 'lib/contracts/invariants.rb', line 44

def expected
  "#{@name} condition to be true"
end