Last active
July 5, 2019 21:11
-
-
Save keithrbennett/08aa675f04353b7c3a9faef2c53cddc8 to your computer and use it in GitHub Desktop.
This file contains 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
# Like the previous gist (https://gist.github.com/keithrbennett/b178fe4b9910bfcc4ed6d76dc5411feb) | |
# but illustrates a use case more similar to the class based approach | |
# illustrated in https://thoughtbot.com/upcase/videos/rack. | |
# In this code, a method is called to return a lambda that calls the passed inner app. | |
# This code is stored at https://gist.github.com/keithrbennett/08aa675f04353b7c3a9faef2c53cddc8. | |
require "rack" | |
require "thin" | |
# Using a StringIO in case strings will be frozen. | |
BODY = StringIO.new | |
INNER_APP = -> (env) do | |
BODY << "Hello World, from the inner middleware.\n" | |
[ 200, { "Content-Type" => "text/plain" }, BODY ] | |
end | |
# Returns a lambda that, when called with the environment, | |
# calls the inner_app parameter. | |
def fn_outer_app(inner) | |
->(env) do | |
status, headers, body = inner.call(env) | |
BODY << "Hello, World, from the outer middleware.\n" | |
[status, headers, BODY.string] | |
end | |
end | |
Rack::Handler::Thin.run(fn_outer_app(INNER_APP)) | |
# Outputs: | |
# | |
# 2019-07-05 16:56:36 -0400. Using partial application... | |
# Hello World, from the inner middleware. | |
# Hello, World, from the outer middleware. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment