使用rackup时,Sinatra静态资源无法找到

11
我有一个使用模块化方式配置的简单Sinatra应用程序。当我按照自述文件中推荐的使用rackup -p 4567启动应用时,位于public文件夹中的静态资源不会被提供。但是当我使用shotgun ./config.ru -p 4567启动它时,它们会被提供。为什么会发生这种情况?这可能在生产中发生吗?
这是我的代码:
# config.ru
require 'rubygems'
require 'bundler'
require 'sinatra'
require 'jammit'

Bundler.require
Jammit.package!


require File.expand_path('./stick.rb')
run Stick

这是应用程序的 Ruby 文件。

require 'sinatra/base'

class Stick < Sinatra::Base
  get '/' do
    haml :index
  end
end
5个回答

16

看起来有两个很好的答案(现有的答案都对我无效)。

首先,在您的config.ru文件中,您可以包含以下内容:

# Replace the directory names to taste
use Rack::Static, :urls => ['/stylesheets', '/javascripts'], :root => 'public'

另外,如果您通过rackup运行应用程序,则:static选项默认设置为false。 您可以通过以下咒语来解决这个问题:

class MyApp < Sinatra::Base
  set :static, true
  # ...
end

4
Sinatra 文档 中得知:当 public 目录存在时,默认情况下会启用 :static 设置。但第二种方法无法帮助我在 Thin 上运行。 - Andrei

3
我有过同样的问题,并且我是这样解决的。 我在我的config.ru文件中添加了这一行。
map "/public" do
  run Rack::Directory.new("./public")
end

我在视图中使用静态文件的方式如下:

%link{:type => 'text/css', :rel => 'stylesheet', :href => '/public/css/reset.css'}
%link{:type => 'text/css', :rel => 'stylesheet', :href => '/public/css/text.css'}
%link{:type => 'text/css', :rel => 'stylesheet', :href => '/public/css/960.css'}
%link{:type => 'text/css', :rel => 'stylesheet', :href => '/public/css/app.css'}

2
首先在你的Sinatra项目中创建一个名为“public”的文件夹,然后添加几个文件夹:
  • stylesheets
  • javascripts
  • images
将CSS、JS和JPG、PNG(图片)添加到每个文件夹中。
最后,像@sirfilip所说,在config.ru文件中添加以下几行代码。
map "/public" do
 run Rack::Directory.new("./public")
end

如果是通用的Sinatra(没有框架默认值),则需要翻译以下内容:

视图/layout.erb

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
 <head>
    ...
    <link rel="stylesheet" href="stylesheets/your_file.css">
    <link rel="icon" type="image/ico" href="images/your_image.ico" />
</head>
<body>
<%= yield %>
...
<script src="javascripts/your_js.js"></script>

views/index.erb

      <div class="margin-bottom-30">
        <div class="row">
          <div class="col-md-12">
            <ul class="nav nav-pills">
              <li class="active"><a href="#">Home <span class="badge">42</span></a></li>
              <li>...</li>
            </ul>          
          </div>
        </div>
      </div>  

你的所有图片、样式表和JavaScript将在你注册在Sinatra应用程序中的任何URL上可用,问题解决了!


2
为了让我在通过config.ru启动的新Sinatra应用程序上正常工作,我需要做其他答案中建议的两件事情:
class MyApp < Sinatra::Base
  set :static, true
  set :root, File.dirname(__FILE__)
end

2

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接