1

我使用 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

请帮忙。怎么做才对?

4

1 回答 1

2

您需要启用 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

之后,您可以将chatschats_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

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

于 2018-06-04T09:07:25.497 回答