Ruby Rack - mounting a simple web server that reads index.html as default

zanona picture zanona · Oct 5, 2010 · Viewed 10.3k times · Source

I'm trying to get some information from this tutorial: http://m.onkey.org/2008/11/18/ruby-on-rack-2-rack-builder

basically I want to have a file config.ru that tell rack to read the current directory so I can access all the files just like a simple apache server and also read the default root with the index.html file...is there any way to do it?

my current config.ru looks like this:

run Rack::Directory.new('')
#this would read the directory but it doesn't set the root to index.html


map '/' do
  file = File.read('index.html')
  run Proc.new {|env| [200, {'Content-Type' => 'text/html'}, file] }
end
#using this reads the index.html mapped as the root but ignores the other files in the directory

So I don't know how to proceed from here...

I've also tried this following the tutorials example but thin doesn't starts properly.

builder = Rack::Builder.new do

  run Rack::Directory.new('')

  map '/' do
    file = File.read('index.html')
    run Proc.new {|env| [200, {'Content-Type' => 'text/html'}, file] }
  end

end

Rack::Handler::Thin.run builder, :port => 3000

Thanks in advance

Answer

valo picture valo · Oct 14, 2010

I think that you are missing the the rackup command. Here is how it is used:

rackup config.ru

This is going to run your rack app on port 9292 using webrick. You can read "rackup --help" for more info how you can change these defaults.

About the app that you want to create. Here is how I think it should look like:

# This is the root of our app
@root = File.expand_path(File.dirname(__FILE__))

run Proc.new { |env|
  # Extract the requested path from the request
  path = Rack::Utils.unescape(env['PATH_INFO'])
  index_file = @root + "#{path}/index.html"

  if File.exists?(index_file)
    # Return the index
    [200, {'Content-Type' => 'text/html'}, File.read(index_file)]
    # NOTE: using Ruby >= 1.9, third argument needs to respond to :each
    # [200, {'Content-Type' => 'text/html'}, [File.read(index_file)]]
  else
    # Pass the request to the directory app
    Rack::Directory.new(@root).call(env)
  end
}