how to make a sinatra app run in rails 4?

2020-07-25 11:15发布

问题:

I have a Sinatra app and I'd like to start building new functionality in Rails while still supporting the existing Sinatra functionality. I've tried the following strategies:

  1. sinatra's rackup routes some requests to rails and some to sinatra
  2. sinatra's rackup includes rails
  3. rails' rackup includes sinatra.

Many of my searches resulted in rails 3, not 4. Additionally, does Rails have to generate the db versus using one that Sinatra was using (in this case, the Sequel gem to access Sqlite3.) In general the errors I was getting were about gems and paths. (Although I did rebundle and try different versions of paths.)

Any suggestions on the best way to use Rails 4 while still supporting an existing Sinatra app?

回答1:

I don't think the Rails/Rack integration code has changed very much between Rails 3 and 4, so you should be fine. The Rails on Rack Guide explains in more detail that you can make a config.ru file for a Rails application that looks like:

require ::File.expand_path('../config/environment',  __FILE__)

use Rack::Debugger
use Rack::ContentLength
run Rails.application

and then running rackup config.ru will start a rack server running your rails app.

The answers to this question point out that if you run Rails and Sinatra from Rack, rather than mounting your Sinatra app in Rails' routes.rb file, requests to your Sinatra app won't go through Rails at all. The answers also show that in your config.ru you should be able to do this to support both your Sinatra and Rails apps:

map "/" do
  run RailsApp::Application
end

map "/url1" do
  run SinatraApp1
end

You'll have to modify the routes and application names to match your needs and your applications, of course.

I'd recommend getting your apps running through one config.ru first, and then ask another question about your databases, explaining in more detail what you'd like the database setup to be and what the exact error messages you're getting are.



回答2:

Rails does not need to create a database or even use one directly. To generate a new Rails app without ActiveRecord, run rails new APP_PATH --skip-active-record. Then, instead of using a database directly from the Rails app, send requests to the Sinatra app and have the Sinatra app control everything database-related.