public
Last active

Rack::Environment is a simple way to easily differentiate the different working environments

  • Download Gist
rack_environment.rb
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62
class RackEnvironment
def initialize(app)
@app = app
@environments = {}
@changes = lambda {}
yield self
end
def call(env)
@env = env
dup._call(env)
end
def _call(env)
@status, @headers, @response = @app.call(env)
@@environment ||= detect_env
if @@environment && modificable?(@response)
@@changes ||= @changes.call(@@environment.first)
@response.body = append_string_to_body(@response.body, @@changes)
@headers["Content-Length"] = @response.body.size.to_s
end
rescue => e
$stderr << e.inspect + "\n"
$stderr << e.backtrace.join("\n") + "\n"
ensure
return [@status, @headers, @response]
end
def define_environment(name, proc)
@environments[name] = proc
end
def append_to_body(proc)
@changes = proc
end
def server_name
@env['SERVER_NAME']
end
private
def modificable?(response)
response.content_type == 'text/html' &&
response.body.kind_of?(String)
rescue
nil
end
def append_string_to_body(html,msg)
html.gsub(/<body[^>]*>/i) { "#{$&}\n#{msg}" }
end
def detect_env
@environments.find{|env_name,proc|
instance_eval(&proc)
}
end
end

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.