ph0rque
ph0rque

Reputation: 194

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

Assuming I have a directory structure similar to:

path_to_file/one/index.html

How can I set my sinatra app to be routed to

mysite.com/path_to_file/one/

and have the previously mentioned file to render? path_to_file will always stay the same, but there will be different folders (two, three, etc.) inside it.

I've tried the following:

get '/path_to_file/:number' do
  File.read(File.join('path_to_file', "#{params[:number]}", "index.html"))
end

but then the e.g. javascript file linked from index.html doesn't render correctly.

Upvotes: 2

Views: 1617

Answers (2)

ph0rque
ph0rque

Reputation: 194

Got it!

get '/path_to_file/:number/:file' do
  File.read(File.join('path_to_file', "#{params[:number]}", "#{params[:file]}"))
end

get '/path_to_file/:number' do
  File.read(File.join('path_to_file', "#{params[:number]}", "index.html"))
end

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'.

Upvotes: 2

jaredonline
jaredonline

Reputation: 2902

Just a thought, but you could setup your server software, Apache, nginx, whatever it is you're using, to serve .css and .js and image files from a different location.

Upvotes: 0

Related Questions