Skip to content

Instantly share code, notes, and snippets.

@stefanpenner
Created August 7, 2008 20:49
Show Gist options
  • Save stefanpenner/4494 to your computer and use it in GitHub Desktop.
Save stefanpenner/4494 to your computer and use it in GitHub Desktop.
require 'rubygems'
require 'yaml'
=begin
Vhost.yml ( path_to_yml_file ) >> Collection of Vhosts
Vhost.new (params) >> Single Vhost
=end
class Vhost
def self.yml(path)
vhosts = []
#load templates
#templates = YAML.load(open(path_to_templates))
## the next two lines are only temp cause i haven't added any of this to the yml file..
templates = Hash.new
templates[:default] = %W{ @options = {
:ServerAlias => "\#{@serverName}",
:DocumentRoot => "/srv/http/\#{@prefix}/\#{@serverName}/htdocs/",
:RewriteEngine => "on",
:RewriteCond => "%{HTTP_HOST} ^www\\.\#{@serverName.gsub('.','\.')}",
:RewriteRule => "(.*) http://\#{@serverName}m$1 [R=301,L]"
}
}
#load hosts yaml file
hosts = YAML.load(open(path))
#parse yaml file
hosts.each do |server,value|
params = Hash.new
options = Hash.new
params[:ServerName] = server
params[:Template] = templates[:default]
# go threw options
value.keys.each do |key|
if key == 'location' # set Prefix
params[:Prefix] = value[key]
elsif key =='type'
#params[:Template] = templates[value[key]]
else # load all other values to options => {...}
options[key.to_sym] = value[key]
end
end
# assign :Options options
params[:Options] = options
# insert new vhost
vhosts << new(params).to_s
end
# return vhosts
vhosts
end
def initialize(arg)
@serverName = arg[:ServerName]
@prefix = arg[:Prefix] unless arg[:Prefix].nil?
#build template
eval arg[:Template].join unless arg[:Template].nil?
# Add option
arg[:Options].each do |key,value|
@options[key] = value
end unless arg[:Options].nil?
end
def to_s
s = []
s << "<VirtualHost *>"
s << "Servername: #{@serverName}"
@options.each do |key,value|
s << "#{key}: #{value}"
end unless @options.nil?
s << "</VirtualHost>"
s
end
end
if __FILE__ == $0
# example custom template
costum = %W{ @options = {
:ServerAlias => "\#{@serverName}",
:DocumentRoot => "/srv/http/\#{@prefix}/\#{@serverName}/htdocs/",
:RewriteEngine => "on",
:RewriteCond => "%{HTTP_HOST} ^www\\.\#{@serverName.gsub('.','\.')}",
:RewriteRule => "(.*) http://\#{@serverName}m$1 [R=301,L]"
}
}
puts Vhost.new(
:ServerName => "sandbox.treehouse11.com",
:Prefix => "stefan",
:Template => costum
).to_s
puts "-"*60
puts Vhost.yml( 'vhosts.yml' )
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment