Module: TryBlock

Defined in:
lib/dolzenko/try_block.rb

Overview

My attempt of [Guarded Evaluation](weblog.raganwald.com/2008/01/objectandand-objectme-in-ruby.html) problem solution. Everyone has that :)

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.install!Object



4
5
6
7
8
9
# File 'lib/dolzenko/try_block.rb', line 4

def self.install!
  unless Object.include?(self)
    Object.send(:include, self)
    Object.send(:public, :try_block)
  end
end

Instance Method Details

#try_block(&block) ⇒ Object

Raises:

  • (ArgumentError)


11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
# File 'lib/dolzenko/try_block.rb', line 11

def try_block(&block)
  raise ArgumentError, "should be given block" unless block

  return if self.nil?

  caller_size = caller.size
  
  # JRuby reports this weird ":1" line in caller
  if RUBY_PLATFORM =~ /\bjava\b/ && caller[-1] == ":1"
    caller_size -= 1
  end
  
  begin
    self.instance_eval(&block)
  rescue NoMethodError => e
    if e.backtrace.size - caller_size == 3 &&
            e.message =~ /^undefined method.+for nil:NilClass$/

      return nil
    end
    raise
  end
end