Skip to content

Instantly share code, notes, and snippets.

@matthutchinson
Created January 14, 2010 08:45
Show Gist options
  • Save matthutchinson/276990 to your computer and use it in GitHub Desktop.
Save matthutchinson/276990 to your computer and use it in GitHub Desktop.
A timesaving subdomain rake task, see here for details; http://matthewhutchinson.net/2010/1/14/a-timesaving-subdomain-rake-task
# subdomains.rake in /lib/tasks
namespace :subdomains do
desc "adds the necessary hosts to your /etc/hosts file from current subdomains in your application"
task :setup => :environment do
# NOTE: default_hosts is used as a locator for the line to update in /etc/hosts
tmp_file, changed = '/tmp/etc_hosts_copy', false
default_hosts, hosts = %w(blog.local emptyblog.blog.local), []
# find all the subdomains used in your app (push to hosts array) - modify this to suit your app
Blog.find(:all).each { |blog| hosts << "#{blog.subdomain}.blog.local" unless blog.subdomain.blank? }
# build hosts line to add/edit
host_line = "127.0.0.1 " + hosts.sort.unshift(default_hosts).join(' ')
# work with a copied hosts file in tmp
%x[cp /etc/hosts #{tmp_file}]
file = File.new(tmp_file)
lines = file.readlines
lines.each do |line|
changed = true if line.gsub!(/^127.0.0.1 #{Regexp.escape(default_hosts.join(' '))}.+$/, host_line)
end
# add line, if no line found for update
lines += ["\n", host_line, "\n"] unless changed
file = File.new(tmp_file,'w')
lines.each { |line| file.write(line) }
file.close
# copy hosts file from tmp - may ask for sudo password
%x[sudo -p "Password:" cp #{tmp_file} /etc/hosts]
# explain what happened
puts "\nAdded the following domains:"
hosts.each { |host| puts "* http://#{host}" }
puts "\nAlso added defaults:"
default_hosts.each { |default| puts "* http://#{default}" }
puts "\n"
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment