类中的路由处理程序

dbg*_*pyd 12 ruby sinatra

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

我正在考虑将post/ getroute处理程序放在类本身内是否是一个更好的结构.

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

class Example
  def say_hello
    "Hello"
  end

  get '/hello' do
    @message = say_hello
  end
end
Run Code Online (Sandbox Code Playgroud)

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

Tod*_*ell 22

你只需要继承Sinatra::Base:

require "sinatra/base"

class Example < Sinatra::Base
  def say_hello
    "Hello"
  end

  get "/hello" do
    say_hello
  end
end
Run Code Online (Sandbox Code Playgroud)

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


如果您需要在应用程序的各个部分之间进行更多分离,请创建另一个Sinatra应用程序.将共享功能放在模型类和帮助程序中,并与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
Run Code Online (Sandbox Code Playgroud)

config.ru:

map "/" do
  run Hello
end

map "/admin" do
  run HelloAdmin
end
Run Code Online (Sandbox Code Playgroud)

安装Thin,然后运行您的应用thin start.