Sha256: cca33fdc8037383044710789293f003464913fe518d87e798ba425c6a22016d8

Contents?: true

Size: 1.42 KB

Versions: 1

Compression:

Stored size: 1.42 KB

Contents

# Copyright (c) 2010-2013 Pluron, Inc.

#Use this to raise internal error with a given message.
#This works for all modes - production, development, etc.
def internal_error(message = 'internal error')
    raise message
end

#Raises internal error when expression evaluates to nil or false
#Use this to check various preconditions, for example
# def do_smth(x)
#   assure(x.is_a? String)
# end
#You can provide optional message to be printed in the exception output.
def assure(expression, message = nil)
    return if expression
    file, method, line = get_caller_location_for_assure

    #Try to find expression in assert
    expression = File.readlines(file)[line.to_i-1].
        gsub(/^.*assure\s*\(\s*/, '').gsub(/\s*\)\s*$/, '')

    #cleanup path - remove rails root and "./"
    if defined? Rails
        file = file.gsub(Rails.root.to_s+'/', '')
    else
        file = file.gsub(Dir.pwd, '')
    end
    file = file.gsub(/^\.\//, '') 
    raise internal_error("#{file}:#{line}: #{method}: Assertion \"#{expression}\" failed#{message ? "\n#{message}" : ""}")
end

def get_caller_location_for_assure(options = {:depth => 2})
    caller_method = caller(options[:depth])[0]

    #Sample output is:
    #   test/unit/assure_test.rb:9:in `test_assure
    #When working dir isn't set, the RAILS_ROOT will be prepended to the path
    caller_method =~ /([^:]+):([0-9]+):in `(.+)'/
    file = $1
    line = $2
    method = $3
    [file, method, line]
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
assure-0.1.1 lib/assure.rb