如果我的Sinatra应用程序结构是这样的。复制自Sinatra帮助
require 'sinatra/base'
class LoginScreen Sinatra::Base
enable :sessions
get('/login') { haml :login }
post('/login') do
if params[:name] == 'admin' && params[:password] == 'admin'
session['user_name'] = params[:name]
else
redirect '/login'
end
end
end
class MyApp Sinatra::Base
# middleware will run before filters
use LoginScreen
before do
unless session['user_name']
halt "Access denied, please login."
end
end
get('/') { "Hello #{session['user_name']}." }
end
问题是两个应用程序是否需要相同的配置,例如助手,寄存器和资产包。如何在不重复代码的情况下使两个应用程序之间保持一致。我可以这样做吗?
require 'sinatra/base'
class LoginScreen Sinatra::Base
include_relative("config_file.rb")
enable :sessions
get('/login') { haml :login }
post('/login') do
if params[:name] == 'admin' && params[:password] == 'admin'
session['user_name'] = params[:name]
else
redirect '/login'
end
end
end
class MyApp Sinatra::Base
# middleware will run before filters
include_relative("config_file.rb")
use LoginScreen
before do
unless session['user_name']
halt "Access denied, please login."
end
end
get('/') { "Hello #{session['user_name']}." }
end
config_file.rb
helpers Sinatra::Helper1
helpers Sinatra::Helper2
helpers Sinatra::Helper3
register Sinatra1
register Sinatra2
register Sinatra3
答案 0 :(得分:3)
如何使用继承?
class MyBase < Sinatra::Base
configure do
helpers Sinatra::Helper1
register Sinatra1
end
end
class LoginScreen < MyBase
end
class MyApp < MyBase
use LoginScreen
end
这种配置在所有来自MyBase
的应用程序之间共享。