Join GitHub today
GitHub is home to over 28 million developers working together to host and review code, manage projects, and build software together.Sign up
Extract several methods from Rack::File#serving #570
Example of Customization
Let's say you have a basic Rack::Directory setup.
But you have a lot of markdown files in the directory, and you want to compile and render them on the fly. That requires modifying the mime type, the response body, and the filesize.
By extracting the methods out of
require 'redcarpet' require 'rack/mime' def markdown_compiler Redcarpet::Markdown.new(Redcarpet::Render::HTML.new) end class Rack::File # Overwrite def mime_type @mime ||= Rack::Mime.mime_type(F.extname(@path), @default_mime) markdown? ? 'text/html' : @mime end # Overwrite def response_body if markdown? @response_body ||= markdown_compiler.render(F.read(@path)) else nil end end def markdown? F.extname(@path) == '.md' end end run Rack::Directory.new(".")
This doesn't change the behavior of Rack, it just makes it easier to customize and to work on in the future. Because of that, I didn't write any tests. Let me know if I should.
I don't think so -- I'm playing around with it here and it seems to be working fine.
If the file hasn't been modified since
Of course, it would be pretty trivial to extract a method (not sure about the name):
def cached? last_modified = F.mtime(@path).httpdate env['HTTP_IF_MODIFIED_SINCE'] == last_modified end
so that whoever's extending it can deal with the problem easier.
Are you talking about the instance variable I set up in the
Then yeah, I think you're right. I was only paying attention to the Rack::Directory scenario, where a new Rack::File is created for each request (at least that's how I understand it).
But if your
Can you confirm that's the problem you're talking about?
I think Rack::File should in future be avoiding setting Content-Length if it cannot determine the size of the body by stat. In the case where it cannot, it should be deferring to Rack::ContentLength and/or Rack::Chunked, to avoid slurping until the last responsible moment.