Простое приложение Roda с маршрутами в отдельных файлах
Я пытаюсь выучить Роду, и у меня возникли небольшие проблемы с переходом на стиль разделения маршрутов в свои файлы. Я получил простое приложение от Roda README и работаю над этим в качестве основы.
Я пытаюсь использовать плагин multi_route. Пока это моя установка:
config.ru
require 'rack/unreloader'
Unreloader = Rack::Unreloader.new { Greeter }
require 'roda'
Unreloader.require './backend.rb'
run Unreloader
backend.rb
require 'roda'
# Class Roda app
class Greeter < Roda
puts 'hey'
plugin :multi_route
puts 'hey hey hey'
route(&:multi_route)
end
Dir['./routes/*.rb'].each { |f| require f }
index.rb
Greeter.route '/' do |r|
r.redirect 'hello'
end
hello.rb
Greeter.route '/hello' do |r|
r.on 'hello' do
puts 'hello'
@greeting = 'helloooooooo'
r.get 'world' do
@greeting = 'hola'
"#{@greeting} world!"
end
r.is do
r.get do
"#{@greeting}!"
end
r.post do
puts "Someone said #{@greeting}!"
r.redirect
end
end
end
end
Итак, теперь, когда я выполняю установку в стойку config.ru и захожу в localhost:9292 в своем браузере, я получаю пустую страницу и 404s в консоли. Что неуместно? Я подозреваю, что я не использую multi_route правильно, но я не уверен.
2 ответа
Вы можете использоватьmulti_run
плагин:
маршруты /foo.rb
module Routes
class Foo < Roda
route do |r|
r.get do
"hello foo"
end
end
end
end
маршруты/bar.rb
module Routes
class Bar < Roda
route do |r|
r.get do
"hello bar"
end
end
end
end
config.ru
require "roda"
Dir['routes/*.rb'].each { |f| require_relative f }
class App < Roda
plugin :multi_run # Allow to group many "r.run" in one call
run 'foo', Routes::Foo # match /foo
run 'bar', Routes::Bar # match /bar
# Same as
# route do |r|
# r.multi_run
# end
route(&:multi_run)
end
run App.freeze.app
Дополнительные альтернативы:
Это немного устарело, но, возможно, это будет полезно кому-то позже.
Для Роды прямая косая черта важна. В вашем примере Greeter.route '/hello' do |r|
Матчи localhost:9292//hello
, и не localhost:9292/hello
,
Вы, вероятно, хотите следующее:
Greeter.route do |r|
r.redirect 'hello'
end
А также это. Что вложено r.on 'hello' do
означает, что эта ветвь дерева только соответствует localhost:9292/hello/hello
а также localhost:9292/hello/hello/world
Это, вероятно, не то, что вы хотели.
Greeter.route 'hello' do |r|
puts 'hello'
@greeting = 'helloooooooo'
r.get 'world' do
@greeting = 'hola'
"#{@greeting} world!"
end
r.is do
r.get do
"#{@greeting}!"
end
r.post do
puts "Someone said #{@greeting}!"
r.redirect
end
end
end