Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Serving static files with Sinatra

Tags:

ruby

sinatra

You can use the send_file helper to serve files.

require 'sinatra'

get '/' do
  send_file File.join(settings.public_folder, 'index.html')
end

This will serve index.html from whatever directory has been configured as having your application's static files.


Without any additional configuration, Sinatra will serve assets in public. For the empty route, you'll want to render the index document.

require 'rubygems'
require 'sinatra'

get '/' do
  File.read(File.join('public', 'index.html'))
end

Routes should return a String which become the HTTP response body. File.read opens a file, reads the file, closes the file and returns a String.


You could just host them from the public folder and they do not need routes.

.
-- myapp.rb
`-- public
    |-- application.css
    |-- application.js
    |-- index.html
    `-- jquery.js

In the myapp.rb

set :public_folder, 'public'

get "/" do
  redirect '/index.html'
end

Link to some sub folder in public

set :public_folder, 'public'
get "/" do
  redirect '/subfolder/index.html' 
end

Everything in ./public is accessible from '/whatever/bla.html

Example :
./public/stylesheets/screen.css
Will be accessible via '/stylesheets/screen.css' no route required


Keep in mind that in production you can have your web server send out index.html automatically so that the request never gets to Sinatra. This is better for performance as you don't have to go through the Sinatra/Rack stack just to serve static text, which is what Apache/Nginx are awesome at doing.


Sinatra should let you serve static files from the public directory as explained in the docs:

Static Files

Static files are served from the ./public directory. You can specify a different location by setting the :public option:

Note that the public directory name is not included in the URL. A file ./public/css/style.css is made available as example.com/css/style.css.