是否可以重写基本 URL?
例如而不是 www.host.com/
使用 www.host.com/blah/
作为
一个基本的 url 等等:
get '/' do
...
end
适用于 www.host.com/blah/
我可以附加到我的所有路线 '/blah/..'
但任何 gem 等。
也将无法工作。
这可以在 Rails 中轻松完成,我也想在 Sinatra 中使用它。
最佳答案
我为此使用了 Rack 中间件 rack-rewrite我对此很满意:)
use Rack::Rewrite do
rewrite %r{^/\w{2}/utils}, '/utils'
rewrite %r{^/\w{2}/ctrl}, '/ctrl'
rewrite %r{^/\w{2}/}, '/'
end
编辑:
不确定我是否理解你的问题,但这里有一个 config.ru
文件
# encoding: utf-8
require './config/trst_conf'
require 'rack-flash'
require 'rack/rewrite'
use Rack::Session::Cookie, :secret => 'zsdgryst34kkufklfSwsqwess'
use Rack::Flash
use Rack::Rewrite do
rewrite %r{^/\w{2}/auth}, '/auth'
rewrite %r{^/\w{2}/utils}, '/utils'
rewrite %r{^/\w{2}/srv}, '/srv'
rewrite %r{^/\w{2}/}, '/'
end
map '/auth' do
run TrstAuth.new
end
map '/utils' do
run TrstUtils.new
end
map '/srv' do
map '/tsk' do
run TrstSysTsk.new
end
map '/' do
run TrstSys.new
end
end
map '/' do
run TrstPub.new
end
和一个示例 Sinatra::Base 子类
# encoding: utf-8
class TrstAuth < Sinatra::Base
# Render stylesheets
get '/stylesheets/:name.css' do
content_type 'text/css', :charset => 'utf-8'
sass :"stylesheets/#{params[:name]}", Compass.sass_engine_options
end
# Render login screen
get '/login' do
haml :"/trst_auth/login", :layout => request.xhr? ? false : :'layouts/trst_pub'
end
# Authentication
post '/login' do
if user = TrstUser.authenticate(params[:login_name], params[:password])
session[:user] = user.id
session[:tasks] = user.daily_tasks
flash[:msg] = {:msg => {:txt => I18n.t('trst_auth.login_msg'), :class => "info"}}.to_json
redirect "#{lang_path}/srv"
else
flash[:msg] = {:msg => {:txt => I18n.t('trst_auth.login_err'), :class => "error"}}.to_json
redirect "#{lang_path}/"
end
end
# Logout
get '/logout' do
session[:user] = nil
session[:daily_tasks] = nil
flash[:msg] = {:msg => {:txt => I18n.t('trst_auth.logout_msg'), :class => "info"}}.to_json
redirect "#{lang_path}/"
end
end
也许这有帮助:) full source on github .
关于ruby - 是否可以在 Sinatra 中重写基本 URL?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6221019/