Class: Saveconf::Base

Inherits:
Object
  • Object
show all
Defined in:
lib/saveconf/config.rb

Overview

Base class for all config. Subclass this to be able to define your own schema.

Constant Summary collapse

@@CURRENT_PATH =
[]
@@GETTER =
Object.new()
@@VALUES =
{}

Class Method Summary collapse

Class Method Details

.def_setter(name) ⇒ Object



72
73
74
75
76
77
78
79
80
81
82
83
84
# File 'lib/saveconf/config.rb', line 72

def self.def_setter(name)
  send :define_singleton_method, name.to_s + '!'  do |value = @@GETTER, &blk|
    if blk != nil
      @@CURRENT_PATH << name
      blk.call
      @@CURRENT_PATH.pop()
    else
      @@CURRENT_PATH << name
      set_value(@@CURRENT_PATH, value)
      @@CURRENT_PATH.pop()
    end
  end
end

.get(path) ⇒ Object



24
25
26
# File 'lib/saveconf/config.rb', line 24

def self.get(path)
  @@VALUES[path]
end

.hash_keys(hash) ⇒ Object



90
91
92
93
94
95
96
97
98
99
# File 'lib/saveconf/config.rb', line 90

def self.hash_keys hash
  res = []
  hash.each_pair do |k,v|
    res << k
    if v.is_a?(Hash)
      res += hash_keys(v)
    end
  end
  res
end

.mk_child_accessor(prefix, hash) ⇒ Object



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

def self.mk_child_accessor(prefix, hash)
  accessor = Accessor.new(@@VALUES, prefix)
  hash.each_pair do |child_name,child|
     if child.is_a?(Hash)
       child_accessor = mk_child_accessor(prefix.dup << child_name, child)
       accessor.instance_eval do
         def child_name
           child_accessor
         end
       end
     else
       accessor.instance_eval <<-"end_eval"
         def #{child_name} *args
           self.get("#{child_name}")
         end
       end_eval
     end
  end
  accessor 
end


101
102
103
104
105
106
# File 'lib/saveconf/config.rb', line 101

def self.print
  @@VALUES.each_pair do |k,v|
    puts "#{k}: #{v}"
  end
  nil
end

.schema(schema_hash) ⇒ Object



28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
# File 'lib/saveconf/config.rb', line 28

def self.schema schema_hash
  @@SCHEMA = schema_hash
  setter = hash_keys(schema_hash)
  setter.each do |setter_name|
    puts "call def_setter for #{setter_name}"
    def_setter(setter_name)
  end

  schema_hash.each_pair do |k,v|
    if v.is_a?(Hash)
      child_accessor = mk_child_accessor([k], v)
      send :define_singleton_method, k do
        child_accessor
      end
    else
      send :define_singleton_method, k do
        @@VALUES[k.to_s]
      end
    end
  end
end

.set_value(keys, value) ⇒ Object



86
87
88
# File 'lib/saveconf/config.rb', line 86

def self.set_value(keys, value)
  @@VALUES[keys.join('.')] = value
end