Class: TinyConfig

Inherits:
BasicObject
Defined in:
lib/tinyconfig.rb,
lib/tinyconfig/version.rb

Constant Summary collapse

VERSION =
"0.0.1"

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeTinyConfig

Returns a new instance of TinyConfig.



45
46
47
# File 'lib/tinyconfig.rb', line 45

def initialize
  @_values = {}
end

Class Method Details

.option(option_name, default = nil, &block) ⇒ Object

### Define new option



7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# File 'lib/tinyconfig.rb', line 7

def option(option_name, default=nil, &block)
  option_name = option_name.to_sym
  getter_name = "__get__#{option_name}".to_sym
  validator = block_given? ? block : nil

  # Private getter method for the default
  # http://www.bofh.org.uk/2007/08/16/a-cunning-evil-trick-with-ruby
  meth = default.respond_to?(:call) ? default : ->{ default }
  define_method(getter_name, &meth)
  private(getter_name)

  define_method option_name do |*args|
    if args.length.zero?
      # No args -> get value
      self.__send__(getter_name)
    else
      # Args provided -> set value (i.e. define getter method on the singleton)
      if validator
        value = validator.call(*args)
      elsif args.length == 1
        value = args.first
      else
        value = args
      end
      meth = value.respond_to?(:call) ? value : ->{ value }
      (class << self ; self ; end).send(:define_method, getter_name, &meth)
    end
  end
end

Instance Method Details

#bulk_loadObject



63
64
65
66
67
68
69
70
# File 'lib/tinyconfig.rb', line 63

def bulk_load
  caller_path = ::Kernel.caller.first.sub(/(:\d+)?(:in .*)?$/, '')
  directory_name = ::File.join(
    ::File.dirname(caller_path),
    ::File.basename(caller_path, ".rb"))
  bulk_glob = ::File.join(directory_name, "*.rb")
  load_helper(bulk_glob)
end

#configure(&block) ⇒ Object



49
50
51
# File 'lib/tinyconfig.rb', line 49

def configure(&block)
  self.instance_eval(&block)
end

#inspectObject Also known as: to_s

Compat methods




76
77
78
79
# File 'lib/tinyconfig.rb', line 76

def inspect
  _values = @_values.sort.map { |k,v| " #{k}=#{v.inspect}" }.join
  "#<#{__realclass__}#{_values}>"
end

#lambda(*args, &block) ⇒ Object



40
41
42
# File 'lib/tinyconfig.rb', line 40

def lambda(*args, &block)
  ::Kernel.lambda(*args, &block)
end

#load(glob) ⇒ Object



53
54
55
56
57
58
59
60
61
# File 'lib/tinyconfig.rb', line 53

def load(glob)
  # If glob is relative, we want to interpret it relative to the
  # calling file (directory that contains the ruby source file that
  # has called the `TinyConfig#load` method) rather than whatever is
  # the process' `Dir.getwd`.

  glob = ::File.expand_path(glob, ::File.dirname(::Kernel.caller.first))
  load_helper(glob)
end