# Used in the pipeline:commit:configure:database Rake task to transform a YAML # file containing common elements from an ActiveRecord database.yml # configuration into a YAML file containing a section for each specified # database environment. It names the databases according to the environment as # well as a client ID. The client ID ensures that multiple build agents can run # tests at the same time even when using a central DB server. # # Example call: # template = ProjectdxPipeline::DatabaseConfigurationTemplate.new('config/database.pipeline.yml') # template.render_to_file('config/database.yml') # # Example template YAML file: # --- # adapter: postgresql # username: postgres_user # password: blahblahblah # host: db.example.com # encoding: UTF8 # min_messages: warning # database_prefix: an_awesome_app # pool: 5 # environments: # - development # - test # class ProjectdxPipeline::DatabaseConfigurationTemplate # the common database config data shared by all environments attr_accessor :config_data # an array containing the names of each database environment to be configured attr_accessor :environments # a string that will prefix the name of each database attr_accessor :database_prefix # a string that will suffix the name of each database, defaults to the # hostname of the machine on which this code is running, but will remove the # "rf-pdx-" prefix and the "(.dyn).renewfund.com" suffix, and it will truncate # the result to be no longer than 63 characters due to PostgreSQL's limitation # on the lenght of database names. attr_accessor :client_id # Instantiates a new configuration template. If a +template_file+ is # specified, it will be loaded as a YAML file and used to read in the # configuration data for the template. def initialize(template_file = nil) @config_data = {} if template_file @config_data = self.class.read_template(template_file) @client_id = @config_data.delete('client_id') @database_prefix = @config_data.delete('database_prefix') @environments = @config_data.delete('environments') end end # returns a Hash containing the ActiveRecord configuration data for all # environments def configuration environments.inject({}) do |config, env_name| config[env_name] = @config_data.dup config[env_name]['database'] = database_name(env_name) config end end # Writes the ActiveRecord configuration data (i.e. config/database.yml) to the # specified file path def render_to_file(path) File.open(path, 'w') do |f| YAML.dump(configuration, f) end end def database_name(environment) #:nodoc: "#{database_prefix}-#{environment}-#{client_id}" end def client_id #:nodoc: @client_id ||= begin client_id = Socket.gethostname.gsub(/\W/, '_') client_id.sub!(/^rf_pdx_/, '') client_id.sub!(/(_dyn)?_renewfund_com$/, '') client_id.slice(0..62) end end def self.read_template(template_file) #:nodoc: YAML.load_file(template_file) end end