Skip to content

Instantly share code, notes, and snippets.

@v2e4lisp
Last active August 29, 2015 14:02
Show Gist options
  • Save v2e4lisp/44fad688aa0f7279f94e to your computer and use it in GitHub Desktop.
Save v2e4lisp/44fad688aa0f7279f94e to your computer and use it in GitHub Desktop.
middle ware pattern
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
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