Search code examples
rubyroda

How to divide nested routes in Roda


I write an application using Roda. I have a nested router like this:

   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

I want to divide one big code-block into two routes like this:

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

Please, help. How to do it right?


Solution

  • You need to enable 2 plugins:

    • multi_route - to allow splitting routes between separate files,
    • shared_vars - to pass variables down the routes.

    Then, on the highest level declare routes as follows:

      # 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
    

    After that you can put chats and chats_messages into separate files:

      # 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
    

    Maybe there is also other solution. I've shared what worked for me. Hope it helps!