类中的路由处理程序 [英] Route Handlers Inside a Class

查看:47
本文介绍了类中的路由处理程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a Sinatra app setup where most of the logic is performed inside of various classes, and the post/get routes instantiate those classes and call their methods.

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

I'm thinking about whether putting the post/get route handlers inside of the classes themselves would be a better structure.

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

In any case, I'd like to know if it is possible. So for instance:

class Example
  def say_hello
    "Hello"
  end

  get '/hello' do
    @message = say_hello
  end
end

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

Without modification to the above, Sinatra will say there is no method say_hello on the SinatraApplication object.

推荐答案

你只需要继承Sinatra::Base:

require "sinatra/base"

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

  get "/hello" do
    say_hello
  end
end

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

You can run your app with Example.run!.

如果您需要在应用程序的各个部分之间进行更多分离,只需制作另一个 Sinatra 应用程序即可.将共享功能放入模型类和助手中,并与 Rack 一起运行您的所有应用.

If you need more separation between parts of your application, just make another Sinatra app. Put shared functionality in model classes and helpers, and run all your apps together with 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 运行您的应用.

Install Thin, and run your app with thin start.

这篇关于类中的路由处理程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆