1

如果我的 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

4

1 回答 1

4

如何使用继承?

class MyBase < Sinatra::Base
  configure do
    helpers Sinatra::Helper1
    register Sinatra1
  end
end

class LoginScreen < MyBase
end

class MyApp < MyBase
  use LoginScreen
end

这种方式配置在所有从MyBase.

于 2012-04-15T00:05:16.927 回答