使Sinatra助手仅在某些路线中可用(模块化应用程序)



我有两个不同版本的应用程序,它们使用某些方法的版本略有不同。

module Sinatra
  class MyApp < Sinatra::Base
    helpers Sinatra::Version1
    helpers Sinatra::Version2
  end
end
module Sinatra
  module Version1
    def say_hello
      puts "Hello from Version1"
    end
  end
  helpers Version1
end
module Sinatra
  module Version2
    def say_hello
      puts "Hello from Version2"
    end
  end
  helpers Version2
end

我意识到以这种方式指定的帮助程序是"顶级",并且可用于所有路由。

我想让不同版本的方法可用于不同的路线。有没有办法在模块化应用程序中实现这一点?

如果您将应用程序拆分为两个不同的模块化类,根据需要"包含"帮助程序,这是可能的。例如:

# config.ru
require './app.rb'
map('/one') do
  run MyApp1
end
map('/two') do
  run MyApp2
end

# app.rb
# helper modules same as you've mentioned above.
class MyApp1 < Sinatra::Base
  helpers Sinatra::Version1
  get '/' do
    say_hello
  end
end
class MyApp2 < Sinatra::Base
  helpers Sinatra::Version2
  get '/' do
    say_hello
  end
end

这是否是最好的方法,我仍然需要思考。

最新更新