lib/conf.rb in conf-0.0.3 vs lib/conf.rb in conf-0.0.4
- old
+ new
@@ -1,9 +1,12 @@
class Conf
class InvalidKeyError < StandardError
end
+
+ class InvalidStateError < StandardError
+ end
def self.configs
@configs ||= {}
end
@@ -18,11 +21,11 @@
end
conf = configs[name] ||= Configuration.new(parent)
conf.instance_eval(&blk)
- conf.freeze
+ conf.lock!
conf
end
def self.get(name)
configs[name] or raise ArgumentError, "no config named #{name.inspect}"
@@ -32,23 +35,37 @@
def initialize(parent = nil)
if parent and not parent.kind_of? self.class
raise TypeError, "expected #{self.class}, got #{parent.inspect}:#{parent.class}"
end
- @parent = parent
- @data = {}
+ @parent = parent
+ @data = {}
@current_nesting = []
+ @locked = false
end
def key?(key)
@data.key?(key) || (@parent && @parent.key?(key))
end
- def freeze
- @parent && @parent.freeze
- super
+ def lock!
+ @locked = true
end
+
+ def unlock!
+ @locked = false
+ end
+
+ def edit(&blk)
+ edit!
+ instance_eval(&blk)
+ done!
+ end
+
+ def locked?
+ @locked
+ end
def section(start_key)
result = @parent ? @parent.section(start_keykey) : {}
@data.each do |key, value|
@@ -79,26 +96,26 @@
def method_missing(meth, *args, &blk)
m = meth.to_s
if m =~ /^(\w+)=/ || args.size == 1
- check_frozen
+ check_lock
key = $1 || m
self[key] = args.first
elsif blk
- check_frozen
+ check_lock
@current_nesting << m
instance_eval(&blk)
@current_nesting.pop
else
obj = self[m]
if obj != nil
@current_nesting.clear
obj
else
@current_nesting << m
- validate_nesting if frozen?
+ validate_nesting if locked?
self
end
end
end
@@ -110,13 +127,13 @@
@current_nesting.clear
raise InvalidKeyError, "no such key: #{current.inspect}"
end
end
- def check_frozen
- if frozen?
+ def check_lock
+ if locked?
@current_nesting.clear
- raise "can't modify frozen config"
+ raise InvalidStateError, "config is locked"
end
end
end
end