Skip to content

Instantly share code, notes, and snippets.

@vinchi777
Last active April 13, 2021 07:47
Show Gist options
  • Save vinchi777/6c5771d506fd28d9c9aaaeacc66c9a25 to your computer and use it in GitHub Desktop.
Save vinchi777/6c5771d506fd28d9c9aaaeacc66c9a25 to your computer and use it in GitHub Desktop.
Chain of responsibility pattern
# frozen_string_literal: true
module ChainOfResponsibility
attr_accessor :next
def handle(result)
@next&.handle(result) || result # Run next handler or return result
end
end
class UploadImage
include ChainOfResponsibility
def handle(job_order)
puts "upload image for #{job_order}"
super(job_order)
end
end
class Notify
include ChainOfResponsibility
def handle(job_order)
puts "notify for #{job_order}"
super(job_order)
end
end
class Update
include ChainOfResponsibility
def handle(job_order)
puts "update for #{job_order}"
super(job_order)
end
end
chain = [UploadImage.new, Update.new, Notify.new]
## Connect chain
chain.inject do |current_klass, next_klass|
current_klass.next = next_klass
end
chain.first.handle('job order')
# upload image for job order
# update for job order
# notify for job order
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment