【问题标题】:Make Sinatra Helpers available only in some routes (modular application)使 Sinatra 助手仅在某些路由中可用(模块化应用程序)
【发布时间】:2017-01-13 02:49:40
【问题描述】:

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

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

我意识到以这种方式指定的助手是“顶级”并且可用于所有路由。

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

【问题讨论】:

    标签: sinatra helpers modular


    【解决方案1】:

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

    # 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
    

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

    【讨论】:

    • 这正是我最终要做的。
    猜你喜欢
    • 1970-01-01
    • 2014-05-23
    • 1970-01-01
    • 1970-01-01
    • 2013-06-19
    • 2013-08-23
    • 2014-09-27
    • 1970-01-01
    • 2012-12-15
    相关资源
    最近更新 更多