Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

Moved some rconfig core code to mixins, to get file size down. Fixed …

…logger.
  • Loading branch information...
commit ce1dce534f552ce53db047fb98f150d5f64a1216 1 parent 94c8c90
Rahmal Conda authored
5 lib/rconfig.rb
View
@@ -25,6 +25,7 @@
autoload :Socket, 'socket'
autoload :YAML, 'yaml'
+autoload :Logger, 'logger'
autoload :Singleton, 'singleton'
require 'rubygems'
@@ -33,8 +34,8 @@
autoload :Hash, 'active_support/core_ext/hash/conversions'
autoload :HashWithIndifferentAccess, 'active_support/core_ext/hash/indifferent_access'
-require 'rconfig/core_ext/object'
-require 'rconfig/core_ext/hash'
+require 'rconfig/mixins'
+require 'rconfig/core_ext'
require 'rconfig/config_hash'
require 'rconfig/logger'
require 'rconfig/properties_file_parser'
61 lib/rconfig/class_variables.rb
View
@@ -1,61 +0,0 @@
-# These are all the variables used to store RConfigs state.
-module ClassVariables
-
- # The list of directories to search for configuration files.
- @@config_paths = []
-
- # Hash of suffixes for a given config name.
- # @@suffixes['name'] vs @@suffix['name_GB']
- @@suffixes = {}
-
- @@overlay = ENV['CONFIG_OVERLAY']
-
- # Hash of yaml file names and their respective contents,
- # last modified time, and the last time it was loaded.
- # @@cache[filename] = [yaml_contents, mod_time, time_loaded]
- @@cache = {}
-
- # Hash of config file base names and their existing filenames
- # including the suffixes.
- # @@cache_files['ldap'] = ['ldap.yml', 'ldap_local.yml', 'ldap_<hostname>.yml']
- @@cache_files = {}
-
- # Hash of config base name and the contents of all its respective
- # files merged into hashes. This hash holds the data that is
- # accessed when RConfig is called. This gets re-created each time
- # the config files are loaded.
- # @@cache_hash['ldap'] = config_hash
- @@cache_hash = {}
-
- # The hash holds the same info as @@cache_hash, but it is only
- # loaded once. If reload is disabled, data will from this hash
- # will always be passed back when RConfig is called.
- @@cache_config_files = {} # Keep around incase reload_disabled.
-
- # Hash of config base name and the last time it was checked for
- # update.
- # @@last_auto_check['ldap'] = Time.now
- @@last_auto_check = {}
-
- # Hash of callbacks Procs for when a particular config file has changed.
- @@on_load = {}
-
- # The number of seconds between reloading of config files
- # and automatic reload checks. Defaults to 5 minutes.
- @@reload_interval = 300
-
- # Flag variable indicating whether or not reload should be executed.
- # Defaults to false.
- @@reload_disabled = false
-
- # Helper variable for white-box testing and debugging.
- # A hash of each file that has been loaded.
- @@config_file_loaded = nil
-
- # Flag indicating whether or not to log errors and
- # errors and application run-time information. It
- # defaults to environment debug level setting, or
- # false if the env variable is not set.
- @@verbose = ((ENV['LOG_LEVEL'] || ENV['DEBUG_LEVEL']).to_s.downcase == 'verbose')
-
-end
52 lib/rconfig/constants.rb
View
@@ -1,52 +0,0 @@
-module Constants
-
- # Sets CONFIG_ROOT to RAILS_ROOT/config unless it has already
- # been defined (i.e. in rails env, or calling ruby app).
- CONFIG_ROOT = RAILS_ROOT + "/config" if defined?(RAILS_ROOT) && defined?(CONFIG_ROOT)
-
- # ENV TIER i.e. (development, integration, staging, or production)
- # Defaults to RAILS_ENV if running in Rails, otherwise, it checks
- # if ENV['TIER'] is present. If not, it assumes production.
- ENV_TIER = (defined?(RAILS_ENV) ? RAILS_ENV : (ENV['TIER'] || 'production')) unless defined? ENV_TIER
-
- # yml, yaml => yaml files, parsable by YAML library
- YML_FILE_TYPES = [:yml, :yaml] unless defined? YML_FILE_TYPES
-
- # xml => self-explanatory
- XML_FILE_TYPES = [:xml] unless defined? XML_FILE_TYPES
-
- # conf, properties => <key=value> based config files
- CNF_FILE_TYPES = [:cnf, :conf, :config, :properties] unless defined? CNF_FILE_TYPES
-
- # The type of file used for config. Valid choices
- # include (yml, yaml, xml, conf, config, properties)
- CONFIG_FILE_TYPES = YML_FILE_TYPES + XML_FILE_TYPES + CNF_FILE_TYPES unless defined? CONFIG_FILE_TYPES
-
- # Use CONFIG_HOSTNAME environment variable to
- # test host-based configurations.
- HOSTNAME = ENV['CONFIG_HOSTNAME'] || Socket.gethostname unless defined? HOSTNAME
-
- # Short Hostname: removes all chars from HOSTNAME, after first "."
- # Used to specify machine-specific config files.
- HOSTNAME_SHORT = HOSTNAME.sub(/\..*$/, '').freeze unless defined? HOSTNAME_SHORT
-
- # This is an array of filename suffixes facilitates overriding
- # configuration (i.e. 'services_local', 'services_development').
- # These files get loaded in order of the array the last file
- # loaded gets splatted on top of everything there.
- # Ex. database_whiskey.yml overrides database_integration.yml
- # overrides database.yml
- SUFFIXES = [nil,
- :local,
- :config, :local_config,
- ENV_TIER, [ENV_TIER, :local],
- HOSTNAME_SHORT, [HOSTNAME_SHORT, :config_local],
- HOSTNAME, [HOSTNAME, :config_local]
- ] unless defined? SUFFIXES
-
- # Used in place of undefined but expected arrays,
- # to prevent creating a bunch of unecesary arrays
- # in memory. See ConfigCore.fire_on_load
- EMPTY_ARRAY = [].freeze unless defined? EMPTY_ARRAY
-
-end
27 lib/rconfig/logger.rb
View
@@ -7,27 +7,32 @@
#
module DefaultLogger
- module MacroMethods
+ module ClassMethods
def create_logger options = {}
- class_inheritable_accessor :default_logger
+ class_inheritable_accessor :default_logger, :options
- logger = Logger.new options[:file] ? options[:file] : STDOUT
- logger.level = options[:level] ? options[:level] : Logger::WARN
- logger.datetime_format = options[:format] ? options[:format] : "%Y-%m-%d %H:%M:%S"
- logger.progname = options[:app_name] ? options[:app_name] : nil
+ self.options = options || {}
+
+ logger = Logger.new( check_options(:file, STDOUT) )
+ logger.level = check_options(:level, ENV['LOG_LEVEL'] || Logger::INFO)
+ logger.datetime_format = check_options(:format, "%Y-%m-%d %H:%M:%S")
+ logger.progname = check_options(:app_name, 'RConfig')
self.default_logger = logger
include DefaultLogger::InstanceMethods
- extend DefaultLogger::ClassMethods
end
- end
-
- module ClassMethods
+
def logger
self.default_logger
end
+
+ def check_options key, default_value=nil
+ puts "Key: #{key.inspect}, Value: #{self.options[key]}, Default: #{default_value}"
+ self.options[key].nil? ? default_value : self.options[key]
+ end
+
end
module InstanceMethods
@@ -37,5 +42,5 @@ def logger
end
end
-Object.class_eval { extend DefaultLogger::MacroMethods }
+Object.class_eval { extend DefaultLogger::ClassMethods }
8 lib/rconfig/mixins.rb
View
@@ -0,0 +1,8 @@
+##
+# Copyright (c) 2009 Rahmal Conda <rahmal@gmail.com>
+#
+require 'rconfig/mixins/constants'
+require 'rconfig/mixins/class_variables'
+require 'rconfig/mixins/config_path'
+require 'rconfig/mixins/overlay'
+require 'rconfig/mixins/load'
57 lib/rconfig/mixins/class_variables.rb
View
@@ -0,0 +1,57 @@
+# These are all the variables used to store RConfigs state.
+module Mixins
+ module ClassVariables
+
+ # The list of directories to search for configuration files.
+ @@config_paths = []
+
+ # Hash of suffixes for a given config name.
+ # @@suffixes['name'] vs @@suffix['name_GB']
+ @@suffixes = {}
+
+ @@overlay = ENV['CONFIG_OVERLAY']
+
+ # Hash of yaml file names and their respective contents,
+ # last modified time, and the last time it was loaded.
+ # @@cache[filename] = [yaml_contents, mod_time, time_loaded]
+ @@cache = {}
+
+ # Hash of config file base names and their existing filenames
+ # including the suffixes.
+ # @@cache_files['ldap'] = ['ldap.yml', 'ldap_local.yml', 'ldap_<hostname>.yml']
+ @@cache_files = {}
+
+ # Hash of config base name and the contents of all its respective
+ # files merged into hashes. This hash holds the data that is
+ # accessed when RConfig is called. This gets re-created each time
+ # the config files are loaded.
+ # @@cache_hash['ldap'] = config_hash
+ @@cache_hash = {}
+
+ # The hash holds the same info as @@cache_hash, but it is only
+ # loaded once. If reload is disabled, data will from this hash
+ # will always be passed back when RConfig is called.
+ @@cache_config_files = {} # Keep around incase reload_disabled.
+
+ # Hash of config base name and the last time it was checked for
+ # update.
+ # @@last_auto_check['ldap'] = Time.now
+ @@last_auto_check = {}
+
+ # Hash of callbacks Procs for when a particular config file has changed.
+ @@on_load = {}
+
+ # The number of seconds between reloading of config files
+ # and automatic reload checks. Defaults to 5 minutes.
+ @@reload_interval = 300
+
+ # Flag variable indicating whether or not reload should be executed.
+ # Defaults to false.
+ @@reload_disabled = false
+
+ # Helper variable for white-box testing and debugging.
+ # A hash of each file that has been loaded.
+ @@config_file_loaded = nil
+
+ end
+end
113 lib/rconfig/mixins/config_paths.rb
View
@@ -0,0 +1,113 @@
+module Mixins
+ module ConfingPaths
+
+ ##
+ # Sets the list of directories to search for
+ # configuration files.
+ # The argument must be an array of strings representing
+ # the paths to the directories, or a string representing
+ # either a single path or a list of paths separated by
+ # either a colon (:) or a semi-colon (;).
+ # If reload is disabled, it can only be set once.
+ def self.config_paths=(paths)
+ return if @@reload_disabled && config_paths_set?
+ if paths.is_a? String
+ path_sep = (paths =~ /;/) ? ';' : ':'
+ paths = paths.split(/#{path_sep}+/)
+ end
+ unless paths.is_a? Array
+ raise ArgumentError,
+ "Path(s) must be a String or an Array [#{paths.inspect}]"
+ end
+ if paths.empty?
+ raise ArgumentError,
+ "Must provide at least one paths: [#{paths.inspect}]"
+ end
+ paths.all? do |dir|
+ dir = CONFIG_ROOT if dir == 'CONFIG_ROOT'
+ unless File.directory?(dir)
+ raise InvalidConfigPathError,
+ "This directory is invalid: [#{dir.inspect}]"
+ end
+ end
+ reload
+ @@config_paths = paths
+ end
+ class << self; alias_method :set_config_paths, :config_paths= end
+
+ ##
+ # Adds the specified path to the list of directories to search for
+ # configuration files.
+ # It only allows one path to be entered at a time.
+ # If reload is disabled, it can onle be set once.
+ def self.set_config_path path
+ return if @@reload_disabled && config_paths_set?
+ return unless path.is_a?(String) # only allow string argument
+ path_sep = (path =~ /;/) ? ';' : ':' # if string contains multiple paths
+ path = path.split(/#{path_sep}+/)[0] # only accept first one.
+
+ if @@config_paths.blank?
+ set_config_paths(path)
+ else
+ config_paths << path if File.directory?(path)
+ reload
+ @@config_paths
+ end
+ end
+ class << self; alias_method :add_config_path, :set_config_path end
+
+ ##
+ # Returns a list of directories to search for
+ # configuration files.
+ #
+ # Can be preset with config_paths=/set_config_path,
+ # controlled via ENV['CONFIG_PATH'],
+ # or defaulted to CONFIG_ROOT (assumming some sort of
+ # application initiation as in RAILS).
+ # Defaults to [ CONFIG_ROOT ].
+ #
+ # Examples:
+ # export CONFIG_PATH="$HOME/work/config:CONFIG_ROOT"
+ # CONFIG_ROOT = RAILS_ROOT + "/config" unless defined? CONFIG_ROOT
+ #
+ def self.config_paths
+ return @@config_paths unless @@config_paths.blank?
+
+ begin
+ config_paths = ENV['CONFIG_PATH']
+ rescue
+ logger.error {
+ "Forget something? No config paths! ENV['CONFIG_PATH'] is not set.\n" +
+ "Hint: Use config_paths= or set_config_path."
+ }
+ end
+
+ begin
+ config_paths = [CONFIG_ROOT]
+ rescue
+ logger.error {
+ "Forget something? No config paths! CONFIG_ROOT is not set.\n" +
+ "Hint: Use config_paths= or set_config_path."
+ }
+ end
+
+ if @@config_paths.blank?
+ raise InvalidConfigPathError,
+ "Forget something? No config paths!\n" +
+ "Niether ENV['CONFIG_PATH'] or CONFIG_ROOT is set.\n" +
+ "Hint: Use config_paths= or set_config_path."
+ end
+
+ @@config_paths
+ end
+
+
+ ##
+ # Indicates whether or not config_paths have been set.
+ # Returns true if @@config_paths has at least one directory.
+ def self.config_paths_set?
+ !@@config_paths.blank?
+ end
+
+ end
+end
54 lib/rconfig/mixins/constants.rb
View
@@ -0,0 +1,54 @@
+module Mixins
+ module Constants
+
+ # Sets CONFIG_ROOT to RAILS_ROOT/config unless it has already
+ # been defined (i.e. in rails env, or calling ruby app).
+ CONFIG_ROOT = RAILS_ROOT + "/config" if defined?(RAILS_ROOT) && defined?(CONFIG_ROOT)
+
+ # ENV TIER i.e. (development, integration, staging, or production)
+ # Defaults to RAILS_ENV if running in Rails, otherwise, it checks
+ # if ENV['TIER'] is present. If not, it assumes production.
+ ENV_TIER = (defined?(RAILS_ENV) ? RAILS_ENV : (ENV['TIER'] || 'production')) unless defined? ENV_TIER
+
+ # yml, yaml => yaml files, parsable by YAML library
+ YML_FILE_TYPES = [:yml, :yaml] unless defined? YML_FILE_TYPES
+
+ # xml => self-explanatory
+ XML_FILE_TYPES = [:xml] unless defined? XML_FILE_TYPES
+
+ # conf, properties => <key=value> based config files
+ CNF_FILE_TYPES = [:cnf, :conf, :config, :properties] unless defined? CNF_FILE_TYPES
+
+ # The type of file used for config. Valid choices
+ # include (yml, yaml, xml, conf, config, properties)
+ CONFIG_FILE_TYPES = YML_FILE_TYPES + XML_FILE_TYPES + CNF_FILE_TYPES unless defined? CONFIG_FILE_TYPES
+
+ # Use CONFIG_HOSTNAME environment variable to
+ # test host-based configurations.
+ HOSTNAME = ENV['CONFIG_HOSTNAME'] || Socket.gethostname unless defined? HOSTNAME
+
+ # Short Hostname: removes all chars from HOSTNAME, after first "."
+ # Used to specify machine-specific config files.
+ HOSTNAME_SHORT = HOSTNAME.sub(/\..*$/, '').freeze unless defined? HOSTNAME_SHORT
+
+ # This is an array of filename suffixes facilitates overriding
+ # configuration (i.e. 'services_local', 'services_development').
+ # These files get loaded in order of the array the last file
+ # loaded gets splatted on top of everything there.
+ # Ex. database_whiskey.yml overrides database_integration.yml
+ # overrides database.yml
+ SUFFIXES = [nil,
+ :local,
+ :config, :local_config,
+ ENV_TIER, [ENV_TIER, :local],
+ HOSTNAME_SHORT, [HOSTNAME_SHORT, :config_local],
+ HOSTNAME, [HOSTNAME, :config_local]
+ ] unless defined? SUFFIXES
+
+ # Used in place of undefined but expected arrays,
+ # to prevent creating a bunch of unecesary arrays
+ # in memory. See ConfigCore.fire_on_load
+ EMPTY_ARRAY = [].freeze unless defined? EMPTY_ARRAY
+
+ end
+end
108 lib/rconfig/mixins/load.rb
View
@@ -0,0 +1,108 @@
+module Mixins
+ module Load
+
+ ##
+ # Register a callback when a config has been reloaded. If no config name
+ # is specified, the callback will be registered under the name :ANY. The
+ # name :ANY will register a callback for any config file change.
+ #
+ # Example:
+ #
+ # class MyClass
+ # @@my_config = { }
+ # RConfig.on_load(:cache) do
+ # @@my_config = { }
+ # end
+ # def my_config
+ # @@my_config ||= something_expensive_thing_on_config(RConfig.cache.memory_limit)
+ # end
+ # end
+ #
+ def self.on_load(*args, &blk)
+ args << :ANY if args.empty?
+ proc = blk.to_proc
+
+ # Call proc on registration.
+ proc.call()
+
+ # Register callback proc.
+ args.each do | name |
+ name = name.to_s
+ (@@on_load[name] ||= [ ]) << proc
+ end
+ end
+
+
+ ##
+ # Sets the flag indicating whether or not reload should be executed.
+ def self.allow_reload=(reload)
+ raise ArgumentError, 'Argument must be true or false.' unless [true, false].include?(reload)
+ @@reload_disabled = (not reload)
+ end
+
+
+ ##
+ # Flag indicating whether or not reload should be executed.
+ def self.reload?
+ !@@reload_disabled
+ end
+
+
+ ##
+ # Sets the number of seconds between reloading of config files
+ # and automatic reload checks. Defaults to 5 minutes.
+ def self.reload_interval=(x)
+ raise ArgumentError, 'Argument must be Integer.' unless x.kind_of?(Integer)
+ @@reload_interval = (x || 300)
+ end
+
+
+ ##
+ # Flushes cached config data, so that it can be reloaded from disk.
+ # It is recommended that this should be used with caution, and any
+ # need to reload in a production setting should minimized or
+ # completely avoided if possible.
+ def self.reload(force = false)
+ raise ArgumentError, 'Argument must be true or false.' unless [true, false].include?(force)
+ if force || reload?
+ flush_cache
+ end
+ nil
+ end
+
+ ##
+ # Disables any reloading of config,
+ # executes &block,
+ # calls check_config_changed,
+ # returns result of block
+ def self.disable_reload(&block)
+ # This should increment @@reload_disabled on entry, decrement on exit.
+ result = nil
+ reload_disabled_save = @@reload_disabled
+ begin
+ @@reload_disabled = true
+ result = yield
+ ensure
+ @@reload_disabled = reload_disabled_save
+ check_config_changed unless @@reload_disabled
+ end
+ result
+ end
+
+protected
+
+ ##
+ # Executes all of the reload callbacks registered to the specified config name,
+ # and all of the callbacks registered to run on any config, as specified by the
+ # :ANY symbol.
+ def self.fire_on_load(name)
+ callbacks =
+ (@@on_load['ANY'] || EMPTY_ARRAY) +
+ (@@on_load[name] || EMPTY_ARRAY)
+ callbacks.uniq!
+ logger.debug "fire_on_load(#{name.inspect}): callbacks[#{callbacks.inspect}]" unless callbacks.empty?
+ callbacks.each{|cb| cb.call()}
+ end
+
+ end
+end
67 lib/rconfig/mixins/overlay.rb
View
@@ -0,0 +1,67 @@
+module Mixins
+ module Overlay
+
+ # Specifies an additional overlay suffix.
+ #
+ # E.g. 'gb' for UK locale.
+ #
+ # Defaults from ENV['CONFIG_OVERLAY'].
+ def self.overlay
+ @@overlay ||= (x = ENV['CONFIG_OVERLAY']) && x.dup.freeze
+ end
+
+
+ ##
+ # Sets overlay for
+ def self.overlay=(x)
+ flush_cache if @@overlay != x
+ @@overlay = x && x.dup.freeze
+ end
+
+
+ ##
+ # Returns a list of suffixes to try for a given config name.
+ #
+ # A config name with an explicit overlay (e.g.: 'name_GB')
+ # overrides any current _overlay.
+ #
+ # This allows code to specifically ask for config overlays
+ # for a particular locale.
+ #
+ def self.suffixes(name)
+ name = name.to_s
+ @@suffixes[name] ||=
+ begin
+ ol = overlay
+ name_x = name.dup
+ if name_x.sub!(/_([A-Z]+)$/, '')
+ ol = $1
+ end
+ name_x.freeze
+ result = if ol
+ ol_ = ol.upcase
+ ol = ol.downcase
+ x = [ ]
+ SUFFIXES.each do | suffix |
+ # Standard, no overlay:
+ # e.g.: database_<suffix>.yml
+ x << suffix
+
+ # Overlay:
+ # e.g.: database_(US|GB)_<suffix>.yml
+ x << [ ol_, suffix ]
+ end
+ [ name_x, x.freeze ]
+ else
+ [ name.dup.freeze, SUFFIXES.freeze ]
+ end
+ result.freeze
+
+ logger.debug {"suffixes(#{name}) => #{result.inspect}"}
+
+ result
+ end
+ end
+
+ end
+end
293 lib/rconfig/rconfig.rb
View
@@ -59,13 +59,15 @@
# ...
#
class RConfig
- include Singleton, Constants, ClassVariables
+ include Singleton,
+ Mixins::Constants, Mixins::ClassVariables,
+ Mixins::ConfigPaths, Mixins::Overlay
create_logger
##
# Convenience method to initialize necessary fields including,
- # config paths, overlay, reload_disabled, and verbose, all at
+ # config path(s), overlay, allow_reload, and log_level, all at
# one time.
def self.initialize(*args)
case args[0]
@@ -74,191 +76,16 @@ def self.initialize(*args)
paths = params[:paths]
overlay = params[:overlay]
reload = params[:reload]
- verbose = params[:verbose]
+ loglvl = params[:log_level]
else
- paths, overlay, reload, verbose = *args
+ paths, overlay, reload, loglvl = *args
end
self.config_paths = paths
self.overlay = overlay
self.allow_reload = reload
- self.verbose = verbose
+ self.log_level = loglvl
end
-
- ##
- # Sets the list of directories to search for
- # configuration files.
- # The argument must be an array of strings representing
- # the paths to the directories, or a string representing
- # either a single path or a list of paths separated by
- # either a colon (:) or a semi-colon (;).
- # If reload is disabled, it can only be set once.
- def self.config_paths=(paths)
- return if @@reload_disabled && config_paths_set?
- if paths.is_a? String
- path_sep = (paths =~ /;/) ? ';' : ':'
- paths = paths.split(/#{path_sep}+/)
- end
- unless paths.is_a? Array
- raise ArgumentError,
- "Path(s) must be a String or an Array [#{paths.inspect}]"
- end
- if paths.empty?
- raise ArgumentError,
- "Must provide at least one paths: [#{paths.inspect}]"
- end
- paths.all? do |dir|
- dir = CONFIG_ROOT if dir == 'CONFIG_ROOT'
- unless File.directory?(dir)
- raise InvalidConfigPathError,
- "This directory is invalid: [#{dir.inspect}]"
- end
- end
- reload
- @@config_paths = paths
- end
- class << self; alias_method :set_config_paths, :config_paths= end
-
-
- ##
- # Adds the specified path to the list of directories to search for
- # configuration files.
- # It only allows one path to be entered at a time.
- # If reload is disabled, it can onle be set once.
- def self.set_config_path path
- return if @@reload_disabled && config_paths_set?
- return unless path.is_a?(String) # only allow string argument
- path_sep = (path =~ /;/) ? ';' : ':' # if string contains multiple paths
- path = path.split(/#{path_sep}+/)[0] # only accept first one.
-
- if @@config_paths.blank?
- set_config_paths(path)
- else
- config_paths << path if File.directory?(path)
- reload
- @@config_paths
- end
- end
- class << self; alias_method :add_config_path, :set_config_path end
-
-
- ##
- # Returns a list of directories to search for
- # configuration files.
- #
- # Can be preset with config_paths=/set_config_path,
- # controlled via ENV['CONFIG_PATH'],
- # or defaulted to CONFIG_ROOT (assumming some sort of
- # application initiation as in RAILS).
- # Defaults to [ CONFIG_ROOT ].
- #
- # Examples:
- # export CONFIG_PATH="$HOME/work/config:CONFIG_ROOT"
- # CONFIG_ROOT = RAILS_ROOT + "/config" unless defined? CONFIG_ROOT
- #
- def self.config_paths
- return @@config_paths unless @@config_paths.blank?
-
- begin
- config_paths = ENV['CONFIG_PATH']
- rescue
- logger.error {
- "Forget something? No config paths! ENV['CONFIG_PATH'] is not set.\n" +
- "Hint: Use config_paths= or set_config_path."
- }
- end
-
- begin
- config_paths = [CONFIG_ROOT]
- rescue
- logger.error {
- "Forget something? No config paths! CONFIG_ROOT is not set.\n" +
- "Hint: Use config_paths= or set_config_path."
- }
- end
-
- if @@config_paths.blank?
- raise InvalidConfigPathError,
- "Forget something? No config paths!\n" +
- "Niether ENV['CONFIG_PATH'] or CONFIG_ROOT is set.\n" +
- "Hint: Use config_paths= or set_config_path."
- end
-
- @@config_paths
- end
-
-
- ##
- # Indicates whether or not config_paths have been set.
- # Returns true if @@config_paths has at least one directory.
- def self.config_paths_set?
- !@@config_paths.blank?
- end
-
-
- # Specifies an additional overlay suffix.
- #
- # E.g. 'gb' for UK locale.
- #
- # Defaults from ENV['CONFIG_OVERLAY'].
- def self.overlay
- @@overlay ||= (x = ENV['CONFIG_OVERLAY']) && x.dup.freeze
- end
-
-
- ##
- # Sets overlay for
- def self.overlay=(x)
- flush_cache if @@overlay != x
- @@overlay = x && x.dup.freeze
- end
-
-
- ##
- # Returns a list of suffixes to try for a given config name.
- #
- # A config name with an explicit overlay (e.g.: 'name_GB')
- # overrides any current _overlay.
- #
- # This allows code to specifically ask for config overlays
- # for a particular locale.
- #
- def self.suffixes(name)
- name = name.to_s
- @@suffixes[name] ||=
- begin
- ol = overlay
- name_x = name.dup
- if name_x.sub!(/_([A-Z]+)$/, '')
- ol = $1
- end
- name_x.freeze
- result = if ol
- ol_ = ol.upcase
- ol = ol.downcase
- x = [ ]
- SUFFIXES.each do | suffix |
- # Standard, no overlay:
- # e.g.: database_<suffix>.yml
- x << suffix
-
- # Overlay:
- # e.g.: database_(US|GB)_<suffix>.yml
- x << [ ol_, suffix ]
- end
- [ name_x, x.freeze ]
- else
- [ name.dup.freeze, SUFFIXES.freeze ]
- end
- result.freeze
-
- logger.debug {"suffixes(#{name}) => #{result.inspect}"}
-
- result
- end
- end
-
-
##
# Get each config file's yaml hash for the given config name,
# to be merged later. Files will only be loaded if they have
@@ -289,11 +116,13 @@ def self.load_config_files(name, force=false)
# it's been loaded before.
val, last_mtime, last_loaded = @@cache[filename]
- logger.debug "f = #{f.inspect}",
- "cache #{name_x} filename = #{filename.inspect}",
- "cache #{name_x} val = #{val.inspect}",
- "cache #{name_x} last_mtime = #{last_mtime.inspect}",
+ logger.debug {
+ "f = #{f.inspect}" +
+ "cache #{name_x} filename = #{filename.inspect}" +
+ "cache #{name_x} val = #{val.inspect}" +
+ "cache #{name_x} last_mtime = #{last_mtime.inspect}" +
"cache #{name_x} last_loaded = #{last_loaded.inspect}"
+ }
# Load the file if its never been loaded or its been more than
# so many minutes since last load attempt. (default: 5 minutes)
@@ -587,95 +416,6 @@ def self.get_config_file(name)
end
- ##
- # Register a callback when a config has been reloaded. If no config name
- # is specified, the callback will be registered under the name :ANY. The
- # name :ANY will register a callback for any config file change.
- #
- # Example:
- #
- # class MyClass
- # @@my_config = { }
- # RConfig.on_load(:cache) do
- # @@my_config = { }
- # end
- # def my_config
- # @@my_config ||= something_expensive_thing_on_config(RConfig.cache.memory_limit)
- # end
- # end
- #
- def self.on_load(*args, &blk)
- args << :ANY if args.empty?
- proc = blk.to_proc
-
- # Call proc on registration.
- proc.call()
-
- # Register callback proc.
- args.each do | name |
- name = name.to_s
- (@@on_load[name] ||= [ ]) << proc
- end
- end
-
-
- ##
- # Sets the flag indicating whether or not reload should be executed.
- def self.allow_reload=(reload)
- raise ArgumentError, 'Argument must be true or false.' unless [true, false].include?(reload)
- @@reload_disabled = (not reload)
- end
-
-
- ##
- # Flag indicating whether or not reload should be executed.
- def self.reload?
- !@@reload_disabled
- end
-
-
- ##
- # Sets the number of seconds between reloading of config files
- # and automatic reload checks. Defaults to 5 minutes.
- def self.reload_interval=(x)
- raise ArgumentError, 'Argument must be Integer.' unless x.kind_of?(Integer)
- @@reload_interval = (x || 300)
- end
-
-
- ##
- # Flushes cached config data, so that it can be reloaded from disk.
- # It is recommended that this should be used with caution, and any
- # need to reload in a production setting should minimized or
- # completely avoided if possible.
- def self.reload(force = false)
- raise ArgumentError, 'Argument must be true or false.' unless [true, false].include?(force)
- if force || reload?
- flush_cache
- end
- nil
- end
-
-
- ##
- # Disables any reloading of config,
- # executes &block,
- # calls check_config_changed,
- # returns result of block
- def self.disable_reload(&block)
- # This should increment @@reload_disabled on entry, decrement on exit.
- result = nil
- reload_disabled_save = @@reload_disabled
- begin
- @@reload_disabled = true
- result = yield
- ensure
- @@reload_disabled = reload_disabled_save
- check_config_changed unless @@reload_disabled
- end
- result
- end
-
##
# Creates a dottable hash for all Hash objects, recursively.
@@ -738,10 +478,13 @@ def [](key)
# Helper method for white-box testing and debugging.
# Sets the flag indicating whether or not to log
# errors and application run-time information.
- def self.verbose=(x)
- @@verbose = x.nil? ? false : x;
+ def self.log_level=(x)
+ logger.level = level unless level.nil?
end
+ def self.log_level
+ logger.level
+ end
##
# Helper method for white-box testing and debugging.
Please sign in to comment.
Something went wrong with that request. Please try again.