任何非平凡的Sinatra应用程序将拥有比想要放入一个大型Sinatra :: Base后代类更多的“路线”。说我想把它们放在另一个班级,什么是惯用语?那个其他阶级的后裔是什么?我如何在主要的Sinatra课程中“包含”它?
您可以在不同的文件中重新打开该类。
# file_a.rb
require 'sinatra'
require_relative "./file_b.rb"
class App < Sinatra::Base
get("/a") { "route a" }
run!
end
# file_b.rb
class App < Sinatra::Base
get("/b") { "route b" }
end
如果你真的想要不同的课程,你可以做这样的事情,但这有点难看:
# file_a.rb
require 'sinatra'
require_relative "./file_b.rb"
class App < Sinatra::Base
get("/a") { "route a" }
extend B
run!
end
# file_b.rb
module B
def self.extended(base)
base.class_exec do
get("/b") { "route b" }
end
end
end
我很确定这两个是最简单的方法。当你查看Sinatra如何从get
这样的方法实际添加路由的源代码时,它非常多毛。
我想你也可以这样做一些傻瓜,但我不会把它称之为惯用语:
# file_a.rb
require 'sinatra'
class App < Sinatra::Base
get("/a") { "route a" }
eval File.read("./file_b.rb")
run!
end
# file_b.rb
get("/b") { "route b" }
为了提供另一种做事方式,您可以随时根据其使用进行组织,例如:
class Frontend < Sinatra::Base
# routes here
get "/" do #…
end
class Admin < Sinatra:Base
# routes with a different focus here
# You can also have things that wouldn't apply elsewhere
# From the docs
set(:auth) do |*roles| # <- notice the splat here
condition do
unless logged_in? && roles.any? {|role| current_user.in_role? role }
redirect "/login/", 303
end
end
end
get "/my/account/", :auth => [:user, :admin] do
"Your Account Details"
end
get "/only/admin/", :auth => :admin do
"Only admins are allowed here!"
end
end
您甚至可以设置基类并从中继承:
module MyAmazingApp
class Base < Sinatra::Base
# a helper you want to share
helpers do
def title=nil
# something here…
end
end
# standard route (see the example from
# the book Sinatra Up and Running)
get '/about' do
"this is a general app"
end
end
class Frontend < Base
get '/about' do
"this is actually the front-end"
end
end
class Admin < Base
#…
end
end
当然,如果您愿意,可以将这些类中的每一个分成单独的文件。运行它们的一种方法:
# config.ru
map("/") do
run MyAmazingApp::Frontend
end
# This would provide GET /admin/my/account/
# and GET /admin/only/admin/
map("/admin") do
MyAmazingApp::Admin
end
还有其他方法,我建议你掌握那本书或查看一些博客文章(这个标签的一些高分者是一个很好的起点)。