我是Sinatra框架的新手,我正在尝试做一个与Sinatra::Base & Sinatra::Application based apps兼容的gem。我的gem中有这个代码,它在两个应用程序中都工作得很好:
health_check.rb
class App1 < Sinatra::Base
get '/health/liveness' do
halt 204
end
end
class App2 < Sinatra::Application
get '/health/liveness' do
halt 204
end
end但我的代码是重复的,我希望有这样的东西,但它不起作用:
health_check.rb
module HealthHelper
get '/health/liveness' do
halt 204
end
end
class App1 < Sinatra::Base
include HealthHelper
end
class App2 < Sinatra::Application
include HealthHelper
end当我尝试初始化任何包含gem的应用程序时,我得到了这个错误
/lib/health_check.rb:3:in `<module:HealthHelper>': undefined method `get' for HealthHelper:Module (NoMethodError)
Did you mean? gets
gem有没有办法让它变得更干净?
发布于 2020-04-18 03:52:36
您可以编写一个定义路由的Sinatra extension,而不是简单地使用include。
它可能看起来像这样:
require 'sinatra/base'
module HealthHelper
def self.registered(app)
app.get '/health/liveness' do
halt 204
end
end
end
# This line is so it will work in classic Sinatra apps.
Sinatra.register(HealthHelper)然后,在实际的应用程序中,您将使用register而不是include
require 'sinatra/base'
require 'health_helper'
class App1 < Sinatra::Base
register HealthHelper
end现在,路由将在App1中可用。请注意,您可能不希望扩展Sinatra::Application,而希望扩展Sinatra::Base。
发布于 2020-04-18 04:04:52
经过多次尝试,我得到了一个非常简单的解决方案:
health_check.rb
class Sinatra::Base
get '/health/liveness' do
halt 204
end
endSinatra::Application是Sinatra:Base的子类,所以我直接将代码包含在Sinatra:Base类定义中。
https://stackoverflow.com/questions/61277245
复制相似问题