Class: Airbrake::Promise
- Inherits:
-
Object
- Object
- Airbrake::Promise
- Defined in:
- lib/airbrake-ruby/promise.rb
Overview
Represents a simplified promise object (similar to promises found in JavaScript), which allows chaining callbacks that are executed when the promise is either resolved or rejected.
Instance Method Summary collapse
-
#initialize ⇒ Promise
constructor
A new instance of Promise.
- #reject(reason = 'rejected') ⇒ self
- #rejected? ⇒ Boolean
-
#rescue {|error| ... } ⇒ self
Attaches a callback to be executed when the promise is rejected.
- #resolve(reason = 'resolved') ⇒ self
- #resolved? ⇒ Boolean
-
#then {|response| ... } ⇒ self
Attaches a callback to be executed when the promise is resolved.
-
#value ⇒ Hash<String,String>
Either successful response containing the
id
key or unsuccessful response containing theerror
key.
Constructor Details
#initialize ⇒ Promise
Returns a new instance of Promise.
10 11 12 13 14 15 |
# File 'lib/airbrake-ruby/promise.rb', line 10 def initialize @on_resolved = [] @on_rejected = [] @value = {} @mutex = Mutex.new end |
Instance Method Details
#reject(reason = 'rejected') ⇒ self
80 81 82 83 84 85 86 87 |
# File 'lib/airbrake-ruby/promise.rb', line 80 def reject(reason = 'rejected') @mutex.synchronize do @value['error'] = reason @on_rejected.each { |callback| callback.call(reason) } end self end |
#rejected? ⇒ Boolean
90 91 92 |
# File 'lib/airbrake-ruby/promise.rb', line 90 def rejected? @value.key?('error') end |
#rescue {|error| ... } ⇒ self
Attaches a callback to be executed when the promise is rejected.
48 49 50 51 52 53 54 55 56 57 58 59 |
# File 'lib/airbrake-ruby/promise.rb', line 48 def rescue(&block) @mutex.synchronize do if @value.key?('error') yield(@value['error']) return self end @on_rejected << block end self end |
#resolve(reason = 'resolved') ⇒ self
66 67 68 69 70 71 72 73 |
# File 'lib/airbrake-ruby/promise.rb', line 66 def resolve(reason = 'resolved') @mutex.synchronize do @value['ok'] = reason @on_resolved.each { |callback| callback.call(reason) } end self end |
#resolved? ⇒ Boolean
95 96 97 |
# File 'lib/airbrake-ruby/promise.rb', line 95 def resolved? @value.key?('ok') end |
#then {|response| ... } ⇒ self
Attaches a callback to be executed when the promise is resolved.
27 28 29 30 31 32 33 34 35 36 37 38 |
# File 'lib/airbrake-ruby/promise.rb', line 27 def then(&block) @mutex.synchronize do if @value.key?('ok') yield(@value['ok']) return self end @on_resolved << block end self end |
#value ⇒ Hash<String,String>
Get rid of this method and use an accessor. The resolved guard is needed for compatibility but it shouldn’t exist in the future
This is a non-blocking call!
Returns either successful response containing the id
key or unsuccessful response containing the error
key.
104 105 106 107 108 |
# File 'lib/airbrake-ruby/promise.rb', line 104 def value return @value['ok'] if resolved? @value end |