module Bard module StagingBanner class Middleware def initialize app @app = app end def call env @status, @headers, @body = @app.call(env) return [@status, @headers, @body] unless html? && !letter_opener_web?(env) response = Rack::Response.new([], @status, @headers) @body.each do |fragment| response.write inject(fragment) end @body.close if @body.respond_to?(:close) response.finish end private def html? @headers["Content-Type"] =~ /html/ end def letter_opener_web? env env["SCRIPT_NAME"].start_with?("/mails") end def mail_count LetterOpenerWeb::Letter.search.length end def inject response count = mail_count mail_link = %((#{mail_count})) if count > 0 html = %(
Staging #{mail_link}
) html += %w[upper-right bottom-left bottom-right].map do |corner| %(
) end.join("\n") markup = html + <<~CSS CSS response.gsub(%r{}, "#{markup}") end end end end