如何在Sinatra的路线中找到更好的结构
我没有发现如何从其他模块混合路由,如下所示:
module otherRoutes get "/route1" do end end class Server < Sinatra::Base include otherRoutes get "/" do #do something end end
那可能吗?
你没有包括 Sinatra。 您将扩展与注册一起使用。
即在单独的文件中构建您的模块:
require 'sinatra/base' module Sinatra module OtherRoutes def self.registered(app) app.get "/route1" do ... end end end register OtherRoutes # for non modular apps, just include this file and it will register end
然后注册:
class Server < Sinatra::Base register Sinatra::OtherRoutes ... end
从文档中可以清楚地看出,这是非基本Sinatra应用程序的方法。 希望它能帮助别人。
你可以这样做:
module OtherRoutes def self.included( app ) app.get "/route1" do ... end end end class Server < Sinatra::Base include OtherRoutes ... end
与Ramaze不同,Sinatra的路由不是方法,因此不能直接使用Ruby的方法查找链接。 请注意,使用此function,您无法在以后对其进行猴子修补,并将更改反映在Server中; 这只是定义路线的一次性便利。
那么你也可以使用map方法将路线映射到你的sinatra应用程序
map "/" do run Rack::Directory.new("./public") end map '/posts' do run PostsApp.new end map '/comments' do run CommentsApp.new end map '/users' do run UserssApp.new end
只是我的两分钱:
my_app.rb:
require 'sinatra/base' class MyApp < Sinatra::Base set :root, File.expand_path('../', __FILE__) set :app_file, __FILE__ disable :run files_to_require = [ "#{root}/app/helpers/**/*.{rb}", "#{root}/app/routes/**/*.{rb}" ] files_to_require.each {|path| Dir.glob(path, &method(:require))} helpers App::Helpers end
应用程序/路由/ health.rb:
MyApp.configure do |c| c.before do content_type "application/json" end c.get "/health" do { Ruby: "#{RUBY_VERSION}", Rack: "#{Rack::VERSION}", Sinatra: "#{Sinatra::VERSION}" }.to_json end end
应用程序/佣工/ application.rb中:
module App module Helpers def t(*args) ::I18n::t(*args) end def h(text) Rack::Utils.escape_html(text) end end end
config.ru:
require './my_app.rb'
我更喜欢使用sinatra-contrib gem来扩展sinatra以获得更清晰的语法和共享命名空间
# Gemfile gem 'sinatra', '~> 1.4.7' gem 'sinatra-contrib', '~> 1.4.6', require: 'sinatra/extension' # other_routes.rb module Foo module OtherRoutes extend Sinatra::Extension get '/some-other-route' do 'some other route' end end end # app.rb module Foo class BaseRoutes < Sinatra::Base get '/' do 'base route' end register OtherRoutes end end
sinata-contrib与sinatra项目一起维护