Roda中如何划分嵌套路由

How to divide nested routes in Roda

我使用 Roda 编写了一个应用程序。 我有一个这样的嵌套路由器:

   route 'chats' do |r|
      env['warden'].authenticate!
      r.is do
        @current_user = env['warden'].user

        r.get do
          # code is here
        end

        r.post do
          # code is here
        end
      end

      r.on :String do |chat_id|
        r.is 'messages' do
          # code is here

          r.get do
            # code is here
          end

          r.post do
            # code is here
          end
        end
      end
    end

我想把一个大代码块分成两条路线:

route 'chats' do |r|
  # code is here
end
route 'chats/:chat_id/messages' do |r, chat_id|
  # code is here
end

请帮忙。怎么做才对?

您需要启用 2 个插件:

然后在最高层声明路由如下:

  # routes/root.rb
  class YourApp::Web
    route do |r|
      r.on('chats') do
        r.is do
          r.route 'chats'
        end

        r.is(String, 'messages') do |chat_id|
          shared[:chat_id] = chat_id
          r.route 'chats_messages'
        end
      end
    end
  end

之后你可以将聊天chats_messages放入单独的文件中:

  # routes/chats.rb
  class YourApp::Web
    route ('chats') do |r|
      r.get do
        # ....
      end

      r.post do
        # ....
      end
    end
  end

  # routes/chats_messages.rb
  class YourApp::Web
    route ('chats_messages') do |r|
      chat_id = shared[:chat_id]
      r.get do  
        # ....
      end

      r.post do  
        # ....
      end
    end
  end

也许还有其他解决方案。我已经分享了对我有用的东西。希望对您有所帮助!