Serving Static Files With Sinatra

Serving static files with Sinatra

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'public', 'index.html'))

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

serving static files on sinatra

You can check the settings object.

irb(main):001:0> require "sinatra"
=> true
irb(main):002:0> settings.public_folder
=> "/usr/lib/ruby/2.5.0/irb/public"

This allows you to create a route which returns the path, something like this

require 'sinatra'

get '/' do

Without more information I would guess that your public folder points to a wrong directory inside your docker because the project :root points to a different directory that what you expect.

Trouble serving static files in Sinatra

For one, I don't believe you need the 'public' in your layout file.


Secondly, I recommend using scss/sass for styling. You just keep the .scss file within your primary /views directory.

- views
- index.haml/html
- style.scss

In your .rb app file:

get '/style.css' do
scss :style

Then, in your view:


Hope that helps!

Serving large static files with Sinatra

I think I can just use send_file (see here) - but if anyone has any other suggestions I have open ears!

Serving static files in Sinatra... with beautiful routes?

Got it!

get '/path_to_file/:number/:file' do'path_to_file', "#{params[:number]}", "#{params[:file]}"))

get '/path_to_file/:number' do'path_to_file', "#{params[:number]}", "index.html"))

Order is important, since if these two methods are reversed, get '/path_to_file/:number' becomes a superset of get '/path_to_file/:number/:file'.

Serving static files from Sinatra with case-insensitive URLs

Here is an idea for your routing:

get '/' do
send_file(File.join(File.dirname(__FILE__), 'public', 'index.html'))

get '*' do
file_path = File.join(File.dirname(__FILE__), 'public', request.path.downcase)
File.exist?(file_path) ? send_file(file_path) : halt 404

not_found do
send_file(File.join(File.dirname(__FILE__), 'public', '404.html'))

This is untested, since I probably won't be able to reproduce your environment anyways. But I think that it would work for your purpose, assuming all your pages are lowercase (as you mentioned) and that you also have an actual 404.html page.

Nginx only serving static files for a Sinatra application

So thanks to @tadman the configuration was ok, the problem was just missing file.

Static page routing in Sinatra (Ruby)

Probably a better answer will eventually come, until then this is my shot at it.

If this is not what you want:

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

You might do something like this:

get '/' do'public/index.html').readlines

I'd go with the first one though, Not sure why you want to avoid that redirect

Related Topics

Leave a reply