-
-
Save practicingruby/2950608 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| module Assertive | |
| FailedConstraint = Class.new(StandardError) | |
| class << self | |
| attr_accessor :enabled | |
| end | |
| def constraints | |
| @constraints ||= [] | |
| end | |
| def constraint(name, &block) | |
| constraints << [name, block] | |
| end | |
| def new(m, *a, &b) | |
| return super unless Assertive.enabled | |
| obj = super | |
| proxy = Object.new | |
| proxy.define_singleton_method(:method_missing) do |m,*a, &b| | |
| obj.class.constraints.each do |name, constraint| | |
| raise(FailedConstraint, name) unless obj.instance_eval(&constraint) | |
| end | |
| obj.send(m, *a, &b) | |
| obj.class.constraints.each do |name, constraint| | |
| raise(FailedConstraint, name) unless obj.instance_eval(&constraint) | |
| end | |
| end | |
| proxy | |
| end | |
| end | |
| class Stack | |
| extend Assertive | |
| constraint("Number of elements must never exceed limit") do | |
| data.size <= limit | |
| end | |
| def initialize(limit) | |
| self.data = [] | |
| self.limit = limit | |
| end | |
| def push(obj) | |
| data.push(obj) | |
| end | |
| def pop | |
| data.pop | |
| end | |
| def merge(other) | |
| self.data = data + other.data | |
| end | |
| protected | |
| attr_accessor :data, :limit | |
| end | |
| Assertive.enabled = true | |
| s = Stack.new(3) | |
| s.push(10) | |
| s.push(15) | |
| s.push(20) | |
| s.push(19) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment