如何在Rails 3中更改默认的rails服务器?

air*_*rin 12 webserver ruby-on-rails ruby-on-rails-3

我是Rails的新手,我想知道是否有一个选项来更改默认的rails服务器,即webrick,用于另一个例如'puma'或'thin'.我知道可以使用'rails server'命令指定运行哪个服务器,但是我想使用此命令而不指定服务器的名称,以便它可以运行默认的rails服务器.有没有办法将默认的rails服务器更改为配置文件或类似的东西?在此先感谢您的帮助!

den*_*lin 20

根据James Hebden答案:

添加Puma到gemfile

# Gemfile
gem 'puma'
Run Code Online (Sandbox Code Playgroud)

捆绑安装它

bundle
Run Code Online (Sandbox Code Playgroud)

将其设为默认值,将此代码粘贴到script/rails上面require 'rails/commands':

require 'rack/handler'
Rack::Handler::WEBrick = Rack::Handler.get(:puma)
Run Code Online (Sandbox Code Playgroud)

所以script/rails(in Rails 3.2.12)看起来像:

#!/usr/bin/env ruby
# This command will automatically be run when you run "rails" with Rails 3 gems installed from the root of your application.

APP_PATH = File.expand_path('../../config/application',  __FILE__)
require File.expand_path('../../config/boot',  __FILE__)
require 'rack/handler'
Rack::Handler::WEBrick = Rack::Handler.get(:puma)
require 'rails/commands'
Run Code Online (Sandbox Code Playgroud)

运行服务器

rails s
=> Booting Puma
Run Code Online (Sandbox Code Playgroud)


Jam*_*den 9

Rack(rails和web服务器之间的接口)具有默认WEBrick和Thin的处理程序.如果将以下内容放在Gemfilerails项目的根目录中

gem 'thin'
Run Code Online (Sandbox Code Playgroud)

rails服务器会自动使用Thin.自3.2rc2以来就是如此.

遗憾的是,这仅适用于Thin,因为Rack没有内置支持Unicorn等.

对于拥有Rack处理程序的服务器(再次,可悲的是Unicorn没有),你可以做一些破解让rails服务器使用它们.在rails项目根目录的scripts/rails文件中,您可以在`require'trail/commands'上面添加以下内容

require 'rack/handler'
Rack::Handler::WEBrick = Rack::Handler::<name of handler class>
Run Code Online (Sandbox Code Playgroud)

这实质上将WEBrick的处理程序重置为指向您要使用的服务器的处理程序.

要了解支持的Rack处理程序,请查看源代码中的注释:https://github.com/rkh/rack/blob/master/lib/rack/handler.rb

  • 应该是`rails/commands`,而不是`rack/commands`.无法编辑你的帖子,愚蠢的StackOverflow说:`编辑必须至少6个字符; 在这篇文章中还有其他改进的地方吗?`:) (2认同)

Yve*_*enn 6

我认为rails只是传递给提供给机架的服务器选项.Rack具有以下逻辑来确定要运行的服务器:

https://github.com/rack/rack/blob/master/lib/rack/server.rb#L271-L273

def server
  @_server ||= Rack::Handler.get(options[:server]) || Rack::Handler.default(options)
end
Run Code Online (Sandbox Code Playgroud)

第一种情况是将:server选项传递给rails server命令.第二是确定默认值.看起来像:

https://github.com/rack/rack/blob/master/lib/rack/handler.rb#L46-L59

def self.default(options = {})
  # Guess.
  if ENV.include?("PHP_FCGI_CHILDREN")
    # We already speak FastCGI
    options.delete :File
    options.delete :Port

    Rack::Handler::FastCGI
  elsif ENV.include?("REQUEST_METHOD")
    Rack::Handler::CGI
  else
    pick ['thin', 'puma', 'webrick']
  end
end
Run Code Online (Sandbox Code Playgroud)

应该自动拾取Thin和Puma.后退是Webrick.当然,其他Web服务器可以覆盖此行为,使其成为链中的第一个.

如果默认情况下没有选择您的Web服务器,您可以将该default方法修改为您想要的工作方式.当然,这可能会在未来版本的机架中出现问题.