Class Amazon::Config
In: lib/amazon.rb
Parent: Hash

A Class for dealing with configuration files, such as /etc/amazonrc and ~/.amazonrc.

Methods

new  

Classes and Modules

Class Amazon::Config::ConfigError

Public Class methods

A configuration may be passed in as a string. Otherwise, the files /etc/amazonrc and ~/.amazonrc are read if they exist and are readable.

[Source]

# File lib/amazon.rb, line 74
    def initialize(config_str=nil)
      locale = nil

      if config_str

        # We have been passed a config file as a string.
        #
        config_files = [ config_str ]
        config_class = StringIO

      else

        # Perform the usual search for the system and user config files.
        #
        config_files = [ File.join( '', 'etc', 'amazonrc' ) ]

        # Figure out where home is. The locations after HOME are for Windows.
        # [ruby-core:12347]
        #
        hp = nil
        if ENV.key?( 'HOMEDRIVE' ) && ENV.key?( 'HOMEPATH' )
          hp = ENV['HOMEDRIVE'] + ENV['HOMEPATH']
        end
        home = ENV['AMAZONRCDIR'] || ENV['HOME'] || hp || ENV['USERPROFILE']

        user_rcfile = ENV['AMAZONRCFILE'] || '.amazonrc'

        if home
          config_files << File.expand_path( File.join( home, user_rcfile ) )
        end

        config_class = File
      end

      config_files.each do |cf|

        if config_class == StringIO
          readable = true
        else
          # We must determine whether the file is readable.
          #
          readable = File.exists?( cf ) && File.readable?( cf )
        end

        if readable

          Amazon.dprintf( 'Opening %s ...', cf ) if config_class == File

          config_class.open( cf ) { |f| lines = f.readlines }.each do |line|
            line.chomp!

            # Skip comments and blank lines.
            #
            next if line =~ /^(#|$)/

            Amazon.dprintf( 'Read: %s', line )

            # Determine whether we're entering the subsection of a new locale.
            #
            if match = line.match( /^\[(\w+)\]$/ )
              locale = match[1]
              Amazon.dprintf( "Config locale is now '%s'.", locale )
              next
            end

            # Store these, because we'll probably find a use for these later.
            #
            begin
              match = line.match( /^\s*(\S+)\s*=\s*(['"]?)([^'"]+)(['"]?)/ )
              key, begin_quote, val, end_quote = match[1, 4]
              raise ConfigError if begin_quote != end_quote

            rescue NoMethodError, ConfigError
              raise ConfigError, "bad config line: #{line}"
            end

            if locale && locale != 'global'
              self[locale] ||= {}
              self[locale][key] = val
            else
              self[key] = val
            end

          end
        end

      end

    end

[Validate]