File: configstruct.rb

package info (click to toggle)
ruby-asetus 0.3.0-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 108 kB
  • sloc: ruby: 248; makefile: 2
file content (80 lines) | stat: -rw-r--r-- 1,617 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
class Asetus
  class ConfigStruct

    def _asetus_to_hash
      hash = {}
      @cfg.each do |key, value|
        if value.class == ConfigStruct
          value = value._asetus_to_hash
        end
        key = key.to_s if @key_to_s
        hash[key] = value
      end
      hash
    end

    def empty?
      @cfg.empty?
    end

    def each &block
      @cfg.each(&block)
    end

    def keys
      @cfg.keys
    end

    def has_key? key
      @cfg.has_key? key
    end

    private

    def initialize hash=nil, opts={}
      @key_to_s = opts.delete :key_to_s
      @cfg = hash ? _asetus_from_hash(hash) : {}
    end

    def method_missing name, *args, &block
      name = name.to_s
      name = args.shift if name[0..1] == '[]' # asetus.cfg['foo']
      arg = args.first
      if    name[-1..-1] == '?'               # asetus.cfg.foo.bar?
        if @cfg.has_key? name[0..-2]
          @cfg[name[0..-2]]
        else
          nil
        end
      elsif name[-1..-1] == '='               # asetus.cfg.foo.bar = 'quux'
        _asetus_set name[0..-2], arg
      else
        _asetus_get name, arg                 # asetus.cfg.foo.bar
      end
    end

    def _asetus_set key, value
      @cfg[key] = value
    end

    def _asetus_get key, value
      if @cfg.has_key? key
        @cfg[key]
      else
        @cfg[key] = ConfigStruct.new
      end
    end

    def _asetus_from_hash hash
      cfg = {}
      hash.each do |key, value|
        if value.class == Hash
          value = ConfigStruct.new value, :key_to_s=>@key_to_s
        end
        cfg[key] = value
      end
      cfg
    end

  end
end