Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I config.ru properly in modular Sinatra application.?

Tags:

ruby

sinatra

rack

I'm trying to use subclassing style in Sinatra application. So, I have a main app 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's only for "GET" how about other resources (e.g. "PUT", "POST")? I'm not sure if I'm missing someting obvious. And also if I have ten path (/path1, /path2, ...) do I have to config them all in config.ru even though they are in the same class?

like image 611
toy Avatar asked Mar 08 '12 08:03

toy


2 Answers

app.rb

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

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

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

  post '/'
  end
end

The config.ru

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
like image 54
Morgan Avatar answered Oct 03 '22 06:10

Morgan


You could write this as

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 documentation at http://www.sinatrarb.com/intro#Serving%20a%20Modular%20Application

like image 44
ch4nd4n Avatar answered Oct 03 '22 08:10

ch4nd4n