类中的路由处理程序

我有一个Sinatra应用程序设置,其中大多数逻辑在各种类中执行, post / get路由实例化这些类并调用它们的方法。

我在考虑是否将post / get路由处理程序放在类本身内是一个更好的结构。

无论如何,我想知道是否有可能。 例如:

 class Example def say_hello "Hello" end get '/hello' do @message = say_hello end end 

如果不修改上述内容,Sinatra会说SinatraApplication对象上没有方法say_hello

你只需要从Sinatra::Baseinheritance:

 require "sinatra/base" class Example < Sinatra::Base def say_hello "Hello" end get "/hello" do say_hello end end 

您可以使用Example.run!运行您的应用程序Example.run!


如果您需要在应用程序的各个部分之间进行更多分离,请创建另一个Sinatra应用程序。 将共享function放在模型类和帮助程序中,并与Rack一起运行所有应用程序。

 module HelloHelpers def say_hello "Hello" end end class Hello < Sinatra::Base helpers HelloHelpers get "/?" do @message = say_hello haml :index end end class HelloAdmin < Sinatra::Base helpers HelloHelpers get "/?" do @message = say_hello haml :"admin/index" end end 

config.ru:

 map "/" do run Hello end map "/admin" do run HelloAdmin end 

安装Thin ,然后使用thin start应用程序。

您可能想要使用Sinatra Helpers 。