/ Published in: Ruby
Niiice... (stolen from linked site via planetrubyonrails.com)
Expand |
Embed | Plain Text
Copy this code and paste it in your HTML
# Encapsulates some object and executes expressions # in the context of that object tracking the result # of the evaluation. As soon as an expression is # false, the verification fails. # # verification = Verifier.new('Marcel') do # try { size == 6 } # Passes # try { size == 5 } # Fails # try { raise } # Doesn't get here # end # # verification.verify # => false class Verifier class FailedVerification < Exception end class << self def verify(object, &block) new(object, &block).verify end end attr_reader :object, :results, :block def initialize(object, &block) @object = object @results = [] @verified = false @block = block end def verified? @verified && results.all? end def verify instance_eval(&block) @verified = true rescue FailedVerification false end def try(&block) results << object.instance_exec(&block) raise FailedVerification if results.last == false end end
URL: http://project.ioni.st/post/1211#snippet_1211