I needed to fire up the Rails 3 server to listen on a port other than the default port 3000. Obviously, I could simply run it like this:
rails server -p 1234
However, for simplicity (and so I wouldn’t forget), I wanted to be able to
configure the alternate port. It seems that the easiest way to accomplish
that goal is by metaprogramming
described in this
However, I didn’t want to hack the port for everyone; I wanted a solution
that would be specific to a
A simple solution
The simplest solution (to me) was to provide for a
file, keyed to each environment. For instance, to allow me to use port 1234
RAILS_ENV is set to
bmc, I’d simply put the following in that file:
# Local configuration. # # NOTE: This file is NOT supplied by Rails. See the logic at the bottom # of boot.rb. # # port - TCP port on which to run the Rails server. Default: 3000 # ----------------------------------------------------------------------- bmc: port: 1234
It’s a simple matter to provide the necessary logic in
Note that the code is more general-purpose than merely what’s necessary to handle a TCP port override.
OPTIONShash defines the default values for various configuration parameters.
fix_config_hashfunction recursively walks through a hash table, converting its string keys to Ruby symbols. It’s used to convert the parsed YAML file into a hash that can be merged with
- The final merged configuration is stored in a
LocalConfigglobal constant, which is accessible elsewhere in the Rails application.
- The configuration YAML file is preparsed with ERB, allowing ERB template logic in the YAML configurations.
When I use the
development environment, Rails listens on the standard port:
$ RAILS_ENV=development rails server Loading local configuration file /home/bmc/src/rails-test/config/config-local.yml => Booting Mongrel => Rails 3.1.0 application starting in development on http://0.0.0.0:3000 => Call with -d to detach => Ctrl-C to shutdown server ^C $
When I use the
bmc environment, Rails listens on port 1234:
$ RAILS_ENV=bmc rails s Loading local configuration file /home/bmc/src/rails-test/config/config-local.yml => Booting Mongrel => Rails 3.1.0 application starting in development on http://0.0.0.0:1234 => Call with -d to detach => Ctrl-C to shutdown server ^C $