Skip to content

Instantly share code, notes, and snippets.

@mplewis
Created February 27, 2017 20:41
Show Gist options
  • Save mplewis/de55fb281ae2aaf12ce224cd5ed74c4f to your computer and use it in GitHub Desktop.
Save mplewis/de55fb281ae2aaf12ce224cd5ed74c4f to your computer and use it in GitHub Desktop.
Basic circuit breaker in Ruby
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
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