Class: Bovem::Configuration

Inherits:
Object
  • Object
show all
Includes:
Lazier::I18n
Defined in:
lib/bovem/configuration.rb

Overview

This class holds the configuration of an applicaton.

Extend this class and add valid properties via property method. Example:

class MyConfiguration << Bovem::Configuration
  property :property, :default => "VALUE"
end

# Configuration file
config.property = "VALUE"

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(file = nil, overrides = {}, logger = nil) ⇒ Configuration

Creates a new configuration.

A configuration file is a plain Ruby file with a top-level config object.

Parameters:

  • file (String) (defaults to: nil)

    The file to read.

  • overrides (Hash) (defaults to: {})

    A set of values which override those set in the configuration file.

  • logger (Logger) (defaults to: nil)

    The logger to use for notifications.

See Also:



32
33
34
35
# File 'lib/bovem/configuration.rb', line 32

def initialize(file = nil, overrides = {}, logger = nil)
  self.i18n_setup(:bovem, ::File.absolute_path(::Pathname.new(::File.dirname(__FILE__)).to_s + "/../../locales/"))
  self.parse(file, overrides, logger)
end

Class Method Details

.property(name, options = {}) ⇒ Object

Defines a new property for the configuration.

Parameters:

  • name (Symbol)

    The name of the property.

  • options (Hash) (defaults to: {})

    A set of options for the property. Currently, only :default (which holds the default value) is supported.



75
76
77
78
79
80
81
82
83
84
85
# File 'lib/bovem/configuration.rb', line 75

def self.property(name, options = {})
  options = {} if !options.is_a?(::Hash)

  define_method(name.to_s) do
    self.instance_variable_get("@#{name}") || options[:default]
  end

  define_method("#{name}=") do |value|
    self.instance_variable_set("@#{name}", value)
  end
end

Instance Method Details

#parse(file = nil, overrides = {}, logger = nil) ⇒ Object

Parses a configuration file.

A configuration file is a plain Ruby file with a top-level config object.

Example:

config.property = "VALUE"

Parameters:

  • file (String) (defaults to: nil)

    The file to read.

  • logger (Logger) (defaults to: nil)

    The logger to use for notifications.

  • overrides (Hash) (defaults to: {})

    A set of values which override those set in the configuration file.



50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
# File 'lib/bovem/configuration.rb', line 50

def parse(file = nil, overrides = {}, logger = nil)
  file = file.present? ? File.expand_path(file) : nil

  if file then
    if File.readable?(file) then
      read_configuration_file(file, logger)
    else
      raise Bovem::Errors::InvalidConfiguration.new(self.i18n.configuration.not_found(file))
    end
  end

  # Apply overrides
  if overrides.is_a?(::Hash) then
    overrides.each_pair do |k, v|
      self.send("#{k}=", v) if self.respond_to?("#{k}=")
    end
  end

  self
end