为 Sinatra::Base 和 Sinatra::Application 类 共享 ruby 代码

Sharing ruby code for Sinatra::Base & Sinatra::Application classes

我对 Sinatra 框架很陌生,我正在尝试做一个 gem 与基于 Sinatra::Base 和 Sinatra::Application 的应用程序兼容。我的 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

有什么办法让它更干净吗?

与其简单地使用 include,您还可以编写定义路由的 Sinatra extension

它可能看起来像这样:

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.

经过多次尝试,我找到了一个非常简单的解决方案:

health_check.rb

class Sinatra::Base
  get '/health/liveness' do
    halt 204
  end
end

Sinatra::Application 是 Sinatra:Base 的子class,所以我将代码直接包含在 Sinatra:Base class 定义中。