如何在开发中更改Rails 3服务器默认端口?

Pie*_*tel 163 ruby-on-rails

在我的开发机器上,我使用端口10524.所以我这样启动我的服务器:

rails s -p 10524
Run Code Online (Sandbox Code Playgroud)

有没有办法将默认端口更改为10524,所以每次启动服务器时都不必附加端口?

Rad*_*sky 131

首先 - 不要在宝石路径中编辑任何内容!它会影响所有项目,你以后会遇到很多问题......

在您的项目编辑中script/rails这样:

#!/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__)

# THIS IS NEW:
require "rails/commands/server"
module Rails
  class Server
    def default_options
      super.merge({
        :Port        => 10524,
        :environment => (ENV['RAILS_ENV'] || "development").dup,
        :daemonize   => false,
        :debugger    => false,
        :pid         => File.expand_path("tmp/pids/server.pid"),
        :config      => File.expand_path("config.ru")
      })
    end
  end
end
# END OF CHANGE
require 'rails/commands'
Run Code Online (Sandbox Code Playgroud)

原理很简单 - 您正在修补服务器运行程序 - 因此它只会影响一个项目.

更新:是的,我知道有更简单的解决方案,包含以下内容的bash脚本:

#!/bin/bash
rails server -p 10524
Run Code Online (Sandbox Code Playgroud)

但是这个解决方案有一个严重的缺点 - 它很无聊.

  • 甚至是别名!`alias rs ='rails server -p 10524'` (14认同)
  • 确保在粘贴的新内容之后放置`require'trail/commands'`.否则它仍然会尝试端口3000. (2认同)

小智 129

我想将以下内容附加到config/boot.rb:

require 'rails/commands/server'

module Rails
  class Server
    alias :default_options_alias :default_options
    def default_options
      default_options_alias.merge!(:Port => 3333)
    end    
  end
end
Run Code Online (Sandbox Code Playgroud)

  • 使用`super`而不是别名hack. (8认同)
  • 使用ruby 2.0,你可以"prepend"一个匿名模块,而不是使用`alias`.这允许干净地使用`super`. (3认同)
  • 不幸的是,如果使用`super`而不是别名,它会调用错误的方法.它调用default_options的`:: Rack :: Server`版本. (2认同)
  • 这个答案将导致“ Rails :: Server”在不应被定义的上下文中定义(例如,运行Rails控制台)。因此,我建议将代码放在“ application.rb”的末尾,并用“如果已定义”(Rails :: Server)保护。 (2认同)

Ros*_*oss 28

还有一个想法.创建一个使用-p调用rails服务器的rake任务.

task "start" => :environment do
  system 'rails server -p 3001'
end
Run Code Online (Sandbox Code Playgroud)

然后打电话rake start而不是rails server


Thi*_*ilo 16

结合两个先前的答案,对于Rails 4.0.4(以及大概,可能),这足以结束config/boot.rb:

require 'rails/commands/server'

module Rails
  class Server
    def default_options
      super.merge({Port: 10524})
    end
  end
end
Run Code Online (Sandbox Code Playgroud)


dec*_*lan 7

我们使用Puma作为Web服务器,并使用dotenv在开发中设置环境变量.这意味着我可以为PORTPuma配置设置环境变量并引用它.

# .env
PORT=10524


# config/puma.rb
port ENV['PORT']
Run Code Online (Sandbox Code Playgroud)

但是,您必须使用foreman start而不是启动您的应用程序rails s,否则puma配置无法正确读取.

我喜欢这种方法,因为配置在开发和生产中的工作方式相同,只需在必要时更改端口的值.