2 # Add these methods to the top-level module so that they are available in all
6 # Defines a constant within a module/class ONLY if that constant does
9 # This can be used to implement defaults in plugins/engines/libraries, e.g.
10 # if a plugin module exists:
12 # default_constant :MyDefault, "the_default_value"
15 # then developers can override this default by defining that constant at
16 # some point *before* the module/plugin gets loaded (such as environment.rb)
17 def default_constant(name, value)
18 if !(name.is_a?(String) or name.is_a?(Symbol))
19 raise "Cannot use a #{name.class.name} ['#{name}'] object as a constant name"
21 if !self.const_defined?(name)
22 self.class_eval("#{name} = #{value.inspect}")
26 # A mechanism for defining configuration of Modules. With this
27 # mechanism, default values for configuration can be provided within shareable
28 # code, and the end user can customise the configuration without having to
34 # config :param_one, "some value"
35 # config :param_two, 12345
38 # Those values can now be accessed by the following method
40 # MyModule.config :param_one
42 # MyModule.config :param_two
45 # ... or, if you have overrriden the method 'config'
47 # MyModule::CONFIG[:param_one]
49 # MyModule::CONFIG[:param_two]
52 # Once a value is stored in the configuration, it will not be altered
53 # by subsequent assignments, unless a special flag is given:
55 # (later on in your code, most likely in another file)
57 # config :param_one, "another value"
58 # config :param_two, 98765, :force
61 # The configuration is now:
63 # MyModule.config :param_one
64 # => "some value" # not changed
65 # MyModule.config :param_two
68 # Configuration values can also be given as a Hash:
70 # MyModule.config :param1 => 'value1', :param2 => 'value2'
72 # Setting of these values can also be forced:
74 # MyModule.config :param1 => 'value3', :param2 => 'value4', :force => true
76 # A value of anything other than false or nil given for the :force key will
77 # result in the new values *always* being set.
80 raise "config expects at least one argument" if args.empty?
82 # extract the arguments
83 if args[0].is_a?(Hash)
84 override = args[0][:force]
85 args[0].delete(:force)
86 args[0].each { |key, value| _handle_config(key, value, override)}
93 # Actually set the config values
94 def _handle_config(name, value=nil, override=false)
95 if !self.const_defined?("CONFIG")
96 self.class_eval("CONFIG = {}")
100 if override or self::CONFIG[name] == nil
101 self::CONFIG[name] = value
104 # if we pass an array of config keys to config(),
105 # get the array of values back
107 name.map { |c| self::CONFIG[c] }