Class: Try

Inherits:
Object
  • Object
show all
Defined in:
lib/Olib/try/try.rb

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(&task) ⇒ Try

Returns a new instance of Try.



10
11
12
13
# File 'lib/Olib/try/try.rb', line 10

def initialize(&task)
  @task = task
  run!
end

Instance Attribute Details

#resultObject

Returns the value of attribute result.



2
3
4
# File 'lib/Olib/try/try.rb', line 2

def result
  @result
end

#taskObject

Returns the value of attribute task.



2
3
4
# File 'lib/Olib/try/try.rb', line 2

def task
  @task
end

Class Method Details

.of(&task) ⇒ Object



4
5
6
7
8
# File 'lib/Olib/try/try.rb', line 4

def self.of(&task)
  Proc.new do 
    Try.new task
  end
end

Instance Method Details

#failed?Boolean

Returns:

  • (Boolean)


29
30
31
# File 'lib/Olib/try/try.rb', line 29

def failed?
  @result.class.ancestors.include? Exception
end

#match?(exp) ⇒ Boolean

Returns:

  • (Boolean)


45
46
47
48
49
50
51
52
53
# File 'lib/Olib/try/try.rb', line 45

def match?(exp)
  if failed?
    @result.message.match(exp)
  elsif @result.respond_to?(:match)
    @result.match(exp)
  else
    raise Exception.new "cannot match class #{@result.class}"
  end
end

#recoverObject



37
38
39
# File 'lib/Olib/try/try.rb', line 37

def recover
  Try.new { yield @result } if failed?
end

#success?Boolean

Returns:

  • (Boolean)


33
34
35
# File 'lib/Olib/try/try.rb', line 33

def success?
  !failed?
end

#thenObject



41
42
43
# File 'lib/Olib/try/try.rb', line 41

def then
  Try.new { yield @result } if success?
end