Created
February 27, 2017 20:41
-
-
Save mplewis/de55fb281ae2aaf12ce224cd5ed74c4f to your computer and use it in GitHub Desktop.
Basic circuit breaker in Ruby
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Breaker | |
def initialize(threshold, debug = false) | |
@active = true | |
@fails = 0 | |
@threshold = threshold | |
@debug = debug | |
@on_trip = nil | |
end | |
def on_trip(&block) | |
@on_trip = block | |
end | |
def pass | |
@active = true | |
@fails = 0 | |
debug | |
end | |
def fail | |
@fails += 1 | |
debug | |
check_break | |
end | |
private | |
def check_break | |
return unless @active | |
return if @fails < @threshold | |
@active = false | |
@on_trip.call if @on_trip | |
end | |
def debug | |
puts "Breaker: #{@active ? 'active' : 'tripped'}, #{@fails}/#{@threshold} fails" if @debug | |
end | |
end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require_relative 'breaker' | |
b = Breaker.new(3, debug: true) | |
b.on_trip do | |
puts 'Tripped!' | |
end | |
b.pass | |
b.pass | |
b.fail | |
b.fail | |
b.fail # Tripped! | |
b.pass | |
b.pass | |
b.fail | |
b.pass | |
b.pass | |
b.fail | |
b.fail | |
b.fail # Tripped! | |
b.fail | |
b.fail |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment