Listen to files directly with Rack TryStatic?

I am using Middleman to create a static site.

Middleman generates static html files in the ./build directory.

Here is the configuration I'm using now:

 require 'rubygems' require 'middleman' require 'rack/contrib/try_static' use Rack::TryStatic, :root => "build", :urls => %w[/], :try => ['.html'] run Middleman::Application.server 

So, Middleman is serving static files right now. How can I make Rack::TryStatic process requests directly?

I tried to do something like

 run Rack::TryStatic, :root => "build", :urls => %w[/], :try => ['.html'] 

But it does not work, running only takes 1 argument. And Rack::TryStatic requires 2 arguments, app and options to initialize, and I don't have an app .

How can i do this?

(And if that matters, I deploy to Heroku)

+4
source share
1 answer

As you noticed, a middleware component for the rack, such as Rack::TryStatic , needs another application to send requests. You can create a simple one to use this, for example, just returned a 404 answer, for example:

 app = lambda {|env| [404, {'Content-type' => 'text/plain'}, ['Not found'] run Rack::TryStatic.new app, :root => "build", :urls => %w[/], :try => ['.html'] 

or equivalently:

 use Rack::TryStatic, :root => "build", :urls => %w[/], :try => ['.html'] run lambda {|env| [404, {'Content-type' => 'text/plain'}, ['Not found']]} 

If you have your own 404 file, you can use the Rack::NotFound instead of your own endpoint:

 use Rack::TryStatic, :root => "build", :urls => %w[/], :try => ['.html'] run Rack::NotFound.new('path/to/your/404.html') 

If you are trying to use an array of file extensions :try , to try and serve, you can directly use Rack::File . Inside Rack::TryStatic uses Rack::Static , which in turn uses Rack::File . Unlike TryStatic and Static , Rack::File is a Rack application in its own right, so a separate application is not required to send requests. Then your config.ru will be simple:

 run Rack::File.new './build' 

although this would not allow bare requests to be served with the corresponding .html file, all requests would need to be fully qualified.

+3
source

All Articles