DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

Add A Fake Host For Development Purposes

02.22.2007
| 5280 views |
  • submit to reddit
        I don't like all these "localhost:3001", "localhost:3001", etc. urls so I use vhosts in apache (that is a proxy balancer for a mongrel cluster on my machine. This script helps me to add required information for my fake domain in the /etc/hosts and apache configs

#!/usr/local/bin/ruby

HOSTS_FILE = "/etc/hosts"
VHOSTS_FILE = "/Library/Apache2/conf/extra/httpd-vhosts.conf"

if $*.size < 2
  puts %{addhost.rb - creates a fake domain and bind it to the working rails app
    
USAGE: addhost development_hostname mongrel_port

Example: if you have a rails app on a localhost:3002 and you want
         to bind it to the myrailsapp.dev than run:
         addhost myrailsapp.dev 3002
  }
  
  exit 1
end

dev_host = $*[0]
mongrel_port = $*[1]

# Adding to the hosts file (absolute path must be in the HOSTS_FILE; usually /etc/hosts)
unless IO.read(HOSTS_FILE) =~ /^127.0.0.1\t#{dev_host}$/
  File.open(HOSTS_FILE, "a") do |file|
    file << "\n127.0.0.1\t#{dev_host}"
  end
end

unless IO.read(VHOSTS_FILE) =~ /^\tServerName #{dev_host}$/
  File.open(VHOSTS_FILE, "a") do |file|
    file << %{
<VirtualHost *:80>
  ServerName #{dev_host}
  
  ProxyPass / http://#{dev_host}:#{mongrel_port}/
  ProxyPassReverse / http://#{dev_host}:#{mongrel_port}
  ProxyPreserveHost on
</VirtualHost>
    }
  end
end