Serving static files with Sinatra

2019-01-07 02:55发布

I have one page website only using HTML, CSS and JavaScript. I want to deploy the app to Heroku, but I cannot find a way to do it. I am now trying to make the app working with Sinatra.

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

And the following is the content of myapp.rb.

require 'rubygems'
require 'sinatra'

get "/" do
  # What should I write here to point to the `index.html`
end

标签: ruby sinatra
14条回答
【Aperson】
2楼-- · 2019-01-07 03:18

You might consider moving the index.html file to views/index.erb, and defining an endpoint like:

get '/' do
  erb :index
end
查看更多
聊天终结者
3楼-- · 2019-01-07 03:20
require 'rubygems'
require 'sinatra'

set :public_folder, File.dirname(__FILE__) + '/../client'
#client - it's folder with all your file, including myapp.rb

get "/" do
  File.read('index.html')
end
查看更多
Animai°情兽
4楼-- · 2019-01-07 03:23

Putting files in public folder has a limitation. Actually, when you are in the root '/' path is works correctly because the browser will set the relative path of your css file for example /css/style.css and sinatra will look for the file in the public directory. However, if your location is for example /user/create, then the web browser will look for your css file in /user/create/css/style.css and will the fail.

As a workaround, I added the following redirection to correctly load css file:

get %r{.*/css/style.css} do
    redirect('css/style.css')
end
查看更多
劳资没心,怎么记你
5楼-- · 2019-01-07 03:26

the sinatra-assetpack gem offers a whole bunch of features. syntax is sweet:

serve '/js', from: '/app/javascripts'

while i am still having issues with rails assets pipeline i feel like i have much more control using sinatra-assetpack - but most of the times it just works with a few lines of code.

查看更多
可以哭但决不认输i
6楼-- · 2019-01-07 03:31

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.

查看更多
Ridiculous、
7楼-- · 2019-01-07 03:31

Add below line in main rb file

set :public_folder, 'public'
查看更多
登录 后发表回答