Skip to content

Instantly share code, notes, and snippets.

@rondy rondy/chain.rb
Created Sep 25, 2015

Embed
What would you like to do?
# encoding: utf-8
module ChainOfResponsibility
attr_writer :successor
def can_handle_request?(request); end
def do_handle(request); end
def handle_request(request)
if can_handle_request?(request)
do_handle(request)
elsif !@successor.nil?
@successor.handle_request(request)
end
end
end
class Carro
include ChainOfResponsibility
def can_handle_request?(request)
request.weight < 1500
end
def do_handle(request)
puts "Um carro é o suficiente para locomover: #{request.weight}"
end
end
class Caminhonete
include ChainOfResponsibility
def can_handle_request?(request)
request.weight < 3000
end
def do_handle(request)
puts "Uma caminhonete é o suficiente para locomover: #{request.weight}"
end
end
class Caminhao
include ChainOfResponsibility
def can_handle_request?(request)
request.weight < 5000
end
def do_handle(request)
puts "Um caminhão é o suficiente para locomover: #{request.weight}"
end
end
class Request
attr_reader :weight
def initialize(weight)
@weight = weight
end
end
class Handler
def initialize
initialize_handlers
setup_successors
end
def handle_request(request)
initial_handler.handle_request(request)
end
private
def initialize_handlers
@carro = Carro.new
@caminhonete = Caminhonete.new
@caminhao = Caminhao.new
end
def setup_successors
@carro.successor = @caminhonete
@caminhonete.successor = @caminhao
end
def initial_handler
@carro
end
end
handler = Handler.new
request = Request.new(1000)
handler.handle_request(request)
request = Request.new(2500)
handler.handle_request(request)
request = Request.new(4500)
handler.handle_request(request)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.