如何在Roda中划分嵌套路由

时间:2018-06-03 14:05:25

标签: ruby 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

请帮忙。怎么做对了?

1 个答案:

答案 0 :(得分:1)

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

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