Class: Contract
- Inherits:
-
Contracts::Decorator
- Object
- Contracts::Decorator
- Contract
- Extended by:
- Contracts::Validators
- Includes:
- Contracts::CallWith
- Defined in:
- lib/contracts.rb
Overview
This is the main Contract class. When you write a new contract, you’ll write it as:
Contract [contract names] => return_value
This class also provides useful callbacks and a validation method.
For #make_validator and related logic see file lib/contracts/validators.rb For #call_with and related logic see file lib/contracts/call_with.rb
Constant Summary collapse
- DEFAULT_FAILURE_CALLBACK =
Default implementation of failure_callback. Provided as a block to be able to monkey patch #failure_callback only temporary and then switch it back. First important usage - for specs.
proc do |data| if data[:return_value] # this failed on the return contract fail ReturnContractError.new(failure_msg(data), data) else # this failed for a param contract fail data[:contracts].failure_exception.new(failure_msg(data), data) end end
Constants included from Contracts::Validators
Contracts::Validators::DEFAULT_VALIDATOR_STRATEGIES
Instance Attribute Summary collapse
-
#args_contracts ⇒ Object
readonly
Returns the value of attribute args_contracts.
-
#klass ⇒ Object
readonly
Returns the value of attribute klass.
-
#method ⇒ Object
readonly
Returns the value of attribute method.
-
#ret_contract ⇒ Object
readonly
Returns the value of attribute ret_contract.
Class Method Summary collapse
-
.failure_callback(data, use_pattern_matching = true) ⇒ Object
Callback for when a contract fails.
-
.failure_msg(data) ⇒ Object
Given a hash, prints out a failure message.
- .fetch_failure_callback ⇒ Object
-
.override_failure_callback(&blk) ⇒ Object
Used to override failure_callback without monkeypatching.
-
.restore_failure_callback ⇒ Object
Used to restore default failure callback.
-
.valid?(arg, contract) ⇒ Boolean
Used to verify if an argument satisfies a contract.
Instance Method Summary collapse
- #[](*args, &blk) ⇒ Object
- #call(*args, &blk) ⇒ Object
-
#failure_exception ⇒ Object
Used to determine type of failure exception this contract should raise in case of failure.
-
#initialize(klass, method, *contracts) ⇒ Contract
constructor
A new instance of Contract.
-
#maybe_append_block!(args, blk) ⇒ Object
a better way to handle this might be to take this into account before throwing a “mismatched # of args” error.
-
#maybe_append_options!(args, blk) ⇒ Object
Same thing for when we have named params but didn’t pass any in.
-
#pattern_match! ⇒ Object
Used internally to mark contract as pattern matching contract.
-
#pattern_match? ⇒ Boolean
Used to determine if contract is a pattern matching contract.
- #pretty_contract(c) ⇒ Object
- #to_s ⇒ Object
Methods included from Contracts::Validators
clean_memoized_validators, make_validator, make_validator!, memoized_validators, override_validator, reset_validators, restore_validators, validator_strategies
Methods included from Contracts::CallWith
Methods inherited from Contracts::Decorator
Constructor Details
#initialize(klass, method, *contracts) ⇒ Contract
Returns a new instance of Contract.
54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 |
# File 'lib/contracts.rb', line 54 def initialize(klass, method, *contracts) unless contracts.last.is_a?(Hash) unless contracts.one? fail %{ It looks like your contract for #{method.name} doesn't have a return value. A contract should be written as `Contract arg1, arg2 => return_value`. }.strip end contracts = [nil => contracts[-1]] end # internally we just convert that return value syntax back to an array @args_contracts = contracts[0, contracts.size - 1] + contracts[-1].keys @ret_contract = contracts[-1].values[0] @args_validators = args_contracts.map do |contract| Contract.make_validator(contract) end @args_contract_index = args_contracts.index do |contract| contract.is_a? Contracts::Args end @ret_validator = Contract.make_validator(ret_contract) @pattern_match = false # == @has_proc_contract last_contract = args_contracts.last is_a_proc = last_contract.is_a?(Class) && (last_contract <= Proc || last_contract <= Method) maybe_a_proc = last_contract.is_a?(Contracts::Maybe) && last_contract.include_proc? @has_proc_contract = is_a_proc || maybe_a_proc || last_contract.is_a?(Contracts::Func) # ==== # == @has_options_contract last_contract = args_contracts.last penultimate_contract = args_contracts[-2] @has_options_contract = if @has_proc_contract penultimate_contract.is_a?(Hash) || penultimate_contract.is_a?(Contracts::Builtin::KeywordArgs) else last_contract.is_a?(Hash) || last_contract.is_a?(Contracts::Builtin::KeywordArgs) end # === @klass, @method = klass, method end |
Instance Attribute Details
#args_contracts ⇒ Object (readonly)
Returns the value of attribute args_contracts.
53 54 55 |
# File 'lib/contracts.rb', line 53 def args_contracts @args_contracts end |
#klass ⇒ Object (readonly)
Returns the value of attribute klass.
53 54 55 |
# File 'lib/contracts.rb', line 53 def klass @klass end |
#method ⇒ Object (readonly)
Returns the value of attribute method.
53 54 55 |
# File 'lib/contracts.rb', line 53 def method @method end |
#ret_contract ⇒ Object (readonly)
Returns the value of attribute ret_contract.
53 54 55 |
# File 'lib/contracts.rb', line 53 def ret_contract @ret_contract end |
Class Method Details
.failure_callback(data, use_pattern_matching = true) ⇒ Object
Callback for when a contract fails. By default it raises an error and prints detailed info about the contract that failed. You can also monkeypatch this callback to do whatever you want…log the error, send you an email, print an error message, etc.
Example of monkeypatching:
def Contract.failure_callback(data)
puts "You had an error!"
puts failure_msg(data)
exit
end
150 151 152 153 154 155 156 |
# File 'lib/contracts.rb', line 150 def self.failure_callback(data, use_pattern_matching = true) if data[:contracts].pattern_match? && use_pattern_matching return DEFAULT_FAILURE_CALLBACK.call(data) end fetch_failure_callback.call(data) end |
.failure_msg(data) ⇒ Object
Given a hash, prints out a failure message. This function is used by the default #failure_callback method and uses the hash passed into the failure_callback method.
118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 |
# File 'lib/contracts.rb', line 118 def self.failure_msg(data) expected = Contracts::Formatters::Expected.new(data[:contract]).contract position = Contracts::Support.method_position(data[:method]) method_name = Contracts::Support.method_name(data[:method]) header = if data[:return_value] "Contract violation for return value:" else "Contract violation for argument #{data[:arg_pos]} of #{data[:total_args]}:" end %{#{header} Expected: #{expected}, Actual: #{data[:arg].inspect} Value guarded in: #{data[:class]}::#{method_name} With Contract: #{data[:contracts]} At: #{position} } end |
.fetch_failure_callback ⇒ Object
178 179 180 |
# File 'lib/contracts.rb', line 178 def self.fetch_failure_callback @failure_callback ||= DEFAULT_FAILURE_CALLBACK end |
.override_failure_callback(&blk) ⇒ Object
Used to override failure_callback without monkeypatching.
Takes: block parameter, that should accept one argument - data.
Example usage:
Contract.override_failure_callback do |data|
puts "You had an error"
puts failure_msg(data)
exit
end
169 170 171 |
# File 'lib/contracts.rb', line 169 def self.override_failure_callback(&blk) @failure_callback = blk end |
.restore_failure_callback ⇒ Object
Used to restore default failure callback
174 175 176 |
# File 'lib/contracts.rb', line 174 def self.restore_failure_callback @failure_callback = DEFAULT_FAILURE_CALLBACK end |
.valid?(arg, contract) ⇒ Boolean
Used to verify if an argument satisfies a contract.
Takes: an argument and a contract.
Returns: a tuple: [Boolean, metadata]. The boolean indicates whether the contract was valid or not. If it wasn’t, metadata contains some useful information about the failure.
189 190 191 |
# File 'lib/contracts.rb', line 189 def self.valid?(arg, contract) make_validator(contract)[arg] end |
Instance Method Details
#[](*args, &blk) ⇒ Object
193 194 195 |
# File 'lib/contracts.rb', line 193 def [](*args, &blk) call(*args, &blk) end |
#call(*args, &blk) ⇒ Object
197 198 199 |
# File 'lib/contracts.rb', line 197 def call(*args, &blk) call_with(nil, *args, &blk) end |
#failure_exception ⇒ Object
Used to determine type of failure exception this contract should raise in case of failure
228 229 230 231 232 233 234 |
# File 'lib/contracts.rb', line 228 def failure_exception if pattern_match? PatternMatchingError else ParamContractError end end |
#maybe_append_block!(args, blk) ⇒ Object
a better way to handle this might be to take this into account before throwing a “mismatched # of args” error. returns true if it appended nil
208 209 210 211 212 213 |
# File 'lib/contracts.rb', line 208 def maybe_append_block! args, blk return false unless @has_proc_contract && !blk && (@args_contract_index || args.size < args_contracts.size) args << nil true end |
#maybe_append_options!(args, blk) ⇒ Object
Same thing for when we have named params but didn’t pass any in. returns true if it appended nil
217 218 219 220 221 222 223 224 225 |
# File 'lib/contracts.rb', line 217 def args, blk return false unless @has_options_contract if @has_proc_contract && (args_contracts[-2].is_a?(Hash) || args_contracts[-2].is_a?(Contracts::Builtin::KeywordArgs)) && !args[-2].is_a?(Hash) args.insert(-2, {}) elsif (args_contracts[-1].is_a?(Hash) || args_contracts[-1].is_a?(Contracts::Builtin::KeywordArgs)) && !args[-1].is_a?(Hash) args << {} end true end |
#pattern_match! ⇒ Object
Used internally to mark contract as pattern matching contract
238 239 240 |
# File 'lib/contracts.rb', line 238 def pattern_match! @pattern_match = true end |
#pattern_match? ⇒ Boolean
Used to determine if contract is a pattern matching contract
243 244 245 |
# File 'lib/contracts.rb', line 243 def pattern_match? @pattern_match == true end |
#pretty_contract(c) ⇒ Object
105 106 107 |
# File 'lib/contracts.rb', line 105 def pretty_contract c c.is_a?(Class) ? c.name : c.class.name end |
#to_s ⇒ Object
109 110 111 112 113 |
# File 'lib/contracts.rb', line 109 def to_s args = args_contracts.map { |c| pretty_contract(c) }.join(", ") ret = pretty_contract(ret_contract) ("#{args} => #{ret}").gsub("Contracts::Builtin::", "") end |