Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

Add design by contract example

  • Loading branch information...
commit 83d4967cf7e133408bfff740e18074e73254a62e 1 parent ddd3056
@gcao authored
Showing with 54 additions and 0 deletions.
  1. +54 −0 examples/design_by_contract.rb
View
54 examples/design_by_contract.rb
@@ -0,0 +1,54 @@
+# Design by contract example
+
+class A
+ def initialize
+ @transactions = []
+ @total = 0
+ end
+
+ def buy price
+ @transactions << price
+ @total += price
+ end
+
+ def sell price
+ @transactions << price # Wrong
+ @total -= price
+ end
+
+end
+
+##############################
+
+$LOAD_PATH.unshift(File.join(File.dirname(__FILE__), '..', 'lib'))
+
+require 'aspector'
+
+class Object
+ def assert bool, message = 'Assertion failure'
+ $stderr.puts message unless bool
+ end
+end
+
+class ContractExample < Aspector::Base
+
+ before do |price, &block|
+ assert price > 0, "Price is #{price}, should be greater than 0"
+ end
+
+ after do |*args, &block|
+ sum = @transactions.reduce(&:+)
+ assert @total == sum, "Total(#{@total}) and sum of transactions(#{sum}) do not match"
+ end
+
+end
+
+##############################
+
+ContractExample.apply A, :methods => %w[buy sell]
+
+a = A.new
+a.buy 10
+a.buy -10
+a.sell 10
+
Please sign in to comment.
Something went wrong with that request. Please try again.