a | b | |
---|
| 0 | + | ['pp', 'yaml'].each{ |lib| require lib } |
---|
| 0 | + | |
---|
| 0 | + | module YAML |
---|
| 0 | + | def save_file(filename, obj) |
---|
| 0 | + | File.open(filename, "w+"){ |file| file.puts(obj.to_yaml) } |
---|
| 0 | + | obj |
---|
| 0 | + | end |
---|
| 0 | + | module_function :save_file |
---|
| 0 | + | end |
---|
| 0 | + | |
---|
| 0 | + | class Hash |
---|
| 0 | + | def rename(old_key, new_key) |
---|
| 0 | + | new_hash = self.dup |
---|
| 0 | + | new_hash[new_key] = new_hash.delete(old_key) |
---|
| 0 | + | new_hash |
---|
| 0 | + | end |
---|
| 0 | + | def rename!(old_key, new_key) |
---|
| 0 | + | self[new_key] = self.delete(old_key) |
---|
| 0 | + | self |
---|
| 0 | + | end |
---|
| 0 | + | end |
---|
| 0 | + | |
---|
| 0 | + | class YAMLOptions |
---|
| 0 | + | attr_accessor :filename |
---|
| 0 | + | alias set instance_eval # Like Object.tap, but evals the block rather than passing self to it |
---|
| 0 | + | |
---|
| 0 | + | def initialize(filename, &blk) |
---|
| 0 | + | @filename = filename |
---|
| 0 | + | @hash = load |
---|
| 0 | + | set(&blk) if block_given? |
---|
| 0 | + | end |
---|
| 0 | + | |
---|
| 0 | + | def method_missing(method, *args, &block) |
---|
| 0 | + | p method |
---|
| 0 | + | end |
---|
| 0 | + | def save |
---|
| 0 | + | YAML.save_file(@filename, @hash) |
---|
| 0 | + | end |
---|
| 0 | + | def load |
---|
| 0 | + | YAML.load_file(@filename) rescue YAML.save_file(@filename, {}) |
---|
| 0 | + | end |
---|
| 0 | + | end |
---|
| 0 | + | |
---|
| 0 | + | options = YAMLOptions.new("./options.yaml") |
---|
| 0 | + | |
---|
| 0 | + | options.set do |
---|
| 0 | + | foo |
---|
| 0 | + | foo = "It aint easy being cheesy!" |
---|
| 0 | + | end |
---|
| 0 | + | puts "#===---" |
---|
| 0 | + | options.foo |
---|
| 0 | + | options.foo = "It aint easy being cheesy!" |
---|
... | |
---|