Last active
August 29, 2015 14:02
-
-
Save v2e4lisp/44fad688aa0f7279f94e to your computer and use it in GitHub Desktop.
middle ware pattern
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
module Middle | |
module Base | |
def self.included(base) | |
base.extend self | |
end | |
def returning value=nil | |
throw :done, value | |
end | |
end | |
def use m, *args | |
middlewares << [m, args] | |
end | |
def middlewares | |
@middlewares ||= [].tap { |this| | |
def this.run(input=nil) | |
catch(:done) { inject(input) { |r, m| m[0].call(r, *m[1]) }} | |
end | |
} | |
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
include Middle | |
class M1 | |
def self.call *args | |
puts *args | |
"From M1" | |
end | |
end | |
class M2 | |
include Middle::Base | |
def self.call *args | |
puts *args | |
returning "return from M2" | |
end | |
end | |
class M3 | |
def self.call *args | |
"M3 untouched" | |
end | |
end | |
use M1 | |
use M2 | |
use M3 | |
result = middlewares.run "hello wolrd" | |
puts result | |
# => hello world | |
# => From M1 | |
# => return from M2 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment