在包含的文件中定义 sinatra 请求路由

Define sinatra request routes in included files

我正在使用 Sinatra,我希望我的项目结构能够将对特定操作的所有请求保存在单独的文件中。

我 运行 遇到的问题是路由没有在 sinatra 中注册,它总是 404s 并运行我的 not_found 处理程序,即使我已经包含了一个文件路线。

这是我正在努力实现的一个例子; Rackup 将启动需要用户和 post 的信息应用程序。 info只包含error and not found handler,相关路由在对应的required文件中。

config.ru:

require 'rubygems'
require 'bundler'

Bundler.require

require 'rack'
require './info.rb'
run Info

info.rb:

require 'rubygems'
require 'bundler'

require 'sinatra'

class Info < Sinatra::Base
    require './user.rb'
    require './post.rb'

    # 500 handler
    error StandardError do
        status 500
        content_type :json
        return '{"error": "Internal server error", "code": 500}'
    end

    not_found do
        status 404
        content_type :json
        return '{"error": "Page not found", "code": 404}'
    end
end

和user.rb(post.rb看起来一样):

require 'rubygems'
require 'bundler'

require 'sinatra'

get '/1/user/:userid' do
    # request stuff
end

require 并不像您认为的那样工作。当您调用 require './user.rb' 时,即使您在 class Info < Sinatra::Base 的主体内执行它,它的内容也不会像在 class 内那样加载。相反,它们在顶层进行解析,并将路由添加到默认值 Sinatra::Application 而不是您的应用程序 class.

您必须在同一个 class 正文中定义您的用户和 post 路由:

#info.rb
require 'sinatra/base' # Require 'sinatra/base' if you are using modular style.

class Info < Sinatra::Base
  # It's a bit unusual to have require inside a class, but not
  # wrong as such, and you might want to have the class defined
  # before loading the other files.
  require_relative 'user.rb' # require_relative is probably safer here.
  require_relative 'post.rb'

  # ... error handlers etc.
end
#user.rb
require 'sinatra/base'

# The routes need to be in the same class.
class Info < Sinatra::Base
  get '/1/user/:userid' do
    # request stuff
  end
end