How to configure config.ru in a modular Sinatra. Application?

I am trying to use a subclass style in a Sinatra application. So, I have a main application like this.

class MyApp < Sinatra::Base get '/' end ... end class AnotherRoute < MyApp get '/another' end post '/another' end end 
 run Rack::URLMap.new \ "/" => MyApp.new, "/another" => AnotherRoute.new 

In config.ru, I understand that it is only for "GET" as about other resources (for example, "PUT", "POST")? I'm not sure I'm missing the obvious. And also, if I have ten paths (/ path1, / path2, ...), do I need to configure them all in config.ru, even if they are in the same class?

+6
source share
3 answers

With the URLMap you specify the base url where the application should be installed. The path indicated on the map is not used to determine which route to use in the application itself. In other words, the application acts as if it were root after the path used in the URLMap .

For example, your code will respond to the following paths:

  • / : will be routed along the route / to MyApp

  • /another : go to route / in AnotherRoute . Since AnotherRoute extends MyApp , it will be the same as / in MyApp (but in a different instance).

    URLMap sees /another and uses it to map to AnotherRoute , removing this part of the request from the path. AnotherRoute then only sees.

  • /another/another : will be redirected to two /another routes in AnotherRoute . Again, the first another used by the URLMap to route the request to AnotherRoute . AnotherRoute then only sees the second another as the path.

    Please note that this path will respond to GET and POST requests, each of which is processed by a corresponding block.

It is not clear what you are trying to do, but I think that you can achieve what you want by running an instance of AnotherRoute from config.ru , which is simple:

 run AnotherRoute.new 

Since AnotherRoute extends MyApp , the route / will be defined for it.

If you are looking for a way to add routes to an existing Sinatra application, you can create a module with the included method that will add routes , rather than using inheritance.

+4
source

app.rb

 class MyApp < Sinatra::Base get '/' end end 

app2.rb If you need two separate files. Note that this inherits from Sinatra :: Base not MyApp.

 class AnotherRoute < Sinatra::Base get '/' end post '/' end end 

Configuration

 require 'bundler/setup' Bundler.require(:default) require File.dirname(__FILE__) + "/lib/app.rb" require File.dirname(__FILE__) + "/lib/app2.rb" map "/" do run MyApp end map "/another" do run AnotherRoute end 
+15
source

You can write it like

 class MyApp < Sinatra::Base get '/' end get '/another' end post '/another' end end 

in config.ru

 require './my_app' run MyApp 

Run:

 rackup -p 1234 

Refer to the documentation at http://www.sinatrarb.com/intro#Serving%20a%20Modular%20Application

+5
source

Source: https://habr.com/ru/post/910230/


All Articles