5

我正在编写一个简单的静态 Rack 应用程序。查看下面的 config.ru 代码:

use Rack::Static, 
  :urls => ["/elements", "/img", "/pages", "/users", "/css", "/js"],
  :root => "archive"


map '/' do
  run Proc.new { |env|
    [
      200, 
      {
        'Content-Type'  => 'text/html', 
        'Cache-Control' => 'public, max-age=6400' 
      },
      File.open('archive/splash.html', File::RDONLY)
    ]
  }
end

map '/pages/search.html' do
  run Proc.new { |env|
    [
      200, 
      {
        'Content-Type'  => 'text/html', 
        'Cache-Control' => 'public, max-age=6400' 
      },
      File.open('archive/pages/search.html', File::RDONLY)
    ]
  }
end

map '/pages/user.html' do
  run Proc.new { |env|
    [
      200, 
      {
        'Content-Type'  => 'text/html', 
        'Cache-Control' => 'public, max-age=6400' 
      },
      File.open('archive/pages/user.html', File::RDONLY)
    ]
  }
end

# Each map section is repeated for each HTML page served

我想通过将 URL 存储为变量并创建一个地图部分来简化这一点

map url do
  run Proc.new { |env|
    [
      200, 
      {
        'Content-Type'  => 'text/html', 
        'Cache-Control' => 'public, max-age=6400' 
      },
      File.open('archive' + url, File::RDONLY)
    ]
  }
end

如何正确设置此 url 变量?

4

2 回答 2

5

怎么样:

static_page_mappings = {
  '/'                  => 'archive/splash.html',
  '/pages/search.html' => 'archive/pages/search.html'
  '/pages/user.html'   => 'archive/pages/user.html',
}

static_page_mappings.each do |req, file|
  map req do 
    run Proc.new { |env|
      [
        200, 
        {
          'Content-Type'  => 'text/html', 
          'Cache-Control' => 'public, max-age=6400',
        },
        File.open(file, File::RDONLY)
      ]
    }
  end
end
于 2012-11-05T03:31:51.633 回答
4

你不应该需要地图部分。

run Proc.new { |env|
  [
    200, 
    {
      'Content-Type'  => 'text/html', 
      'Cache-Control' => 'public, max-age=6400' 
    },
    File.open( 'archive' + env['PATH_INFO'], File::RDONLY)
  ]
}
于 2012-11-05T03:01:43.180 回答