Class: DotConfig::Configuration

Inherits:
Object
  • Object
show all
Defined in:
lib/dot_config/configuration.rb

Overview

This class gives you access to the configuration with dot syntax.

Examples:

Using the dot syntax (readonly):

app_config = DotConfig::Configuration.new #=> #<DotConfig::Configuration:0x007fa5d38f4fa0>
app_config.config = { ruby: { rails => '4.0.0', sinatra: '1.3.3' } }
app_config.ruby.rails #=> '4.0.0'
app_config.python     #=> NoMethodError: undefined method `python' for #<DotConfig::Configuration:0x007fa5d38c23c0>

Using the dot syntax:

app_config = DotConfig::Configuration.new(writing: true) #=> #<DotConfig::Configuration:0x007fa5d38f4fa0>
app_config.config = { ruby: { rails => '4.0.0', sinatra: '1.3.3' } }
app_config.ruby.rails #=> '4.0.0'
app_config.ruby.rails = '3.2.9'
app_config.ruby.rails #=> '3.2.9'

Author:

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(options = {}) ⇒ self

Class constructor.

Raises:

  • (ArgumentError)


30
31
32
33
34
35
# File 'lib/dot_config/configuration.rb', line 30

def initialize(options = {})
  raise ArgumentError, 'Invalid argument' if !options.is_a?(Hash)

  @writing    = options[:writing] ? true : false
  self.config = options[:config] if options[:config].is_a?(Hash)
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(name, *arguments) ⇒ Object

Post treatment of call method which have failed.

Parameters:

  • name (Symbol)

    The name of the method called.

  • arguments (Array)

    The arguments provided with the call.

Returns:

  • (Object)

    The value of the config or call the super method.



60
61
62
63
64
65
66
67
68
69
70
71
72
# File 'lib/dot_config/configuration.rb', line 60

def method_missing(name, *arguments)
  if name[-1, 1] == '=' && @config.key?(name[0..-2].to_sym)
    if @writing
      @config[name[0..-2].to_sym] = arguments.first
    else
      raise 'The configuration is not allowed in writing'
    end
  elsif @config.key?(name)
    @config[name]
  else
    super
  end
end

Instance Attribute Details

#configHash

Returns Stores the configuration like a Hash.

Returns:

  • (Hash)

    Stores the configuration like a Hash.



25
26
27
# File 'lib/dot_config/configuration.rb', line 25

def config
  @config
end

#writingObject (readonly)

Returns the value of attribute writing.



25
# File 'lib/dot_config/configuration.rb', line 25

attr_reader :config, :writing

Instance Method Details

#to_hashHash

Returns the config like a Hash.

Returns:

  • (Hash)

    The original hash with keys symbolized.



77
78
79
80
81
# File 'lib/dot_config/configuration.rb', line 77

def to_hash
  hash = Hash.new
  @config.each { |k, v| hash[k] = v.is_a?(self.class) ? v.to_hash : v }
  hash
end