Rack: How do you store the URL as a variable?

假装没事ソ 提交于 2019-12-21 05:01:01

问题


I am writing a simple static Rack app. Check out the config.ru code below:

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

I'd like to simplify this by storing the URL as variable and creating one map section that says

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

How can I correctly set this url variable?


回答1:


You shouldn't need the map part.

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



回答2:


How about:

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


来源:https://stackoverflow.com/questions/13225343/rack-how-do-you-store-the-url-as-a-variable

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!