lib/yaml_master.rb in yaml_master-0.2.0 vs lib/yaml_master.rb in yaml_master-0.3.0
- old
+ new
@@ -1,16 +1,23 @@
require "yaml_master/version"
require "yaml"
require "erb"
require "pathname"
+require "pp"
YAML.add_domain_type(nil, "include") do |type, val|
YAML.load_file(val)
end
class YamlMaster
+ class KeyFetchError < StandardError
+ def initialize(data, key)
+ super("cannot fetch key \"#{key}\" from\n#{data.pretty_inspect}")
+ end
+ end
+
attr_reader :master, :master_path
def initialize(io_or_filename)
embedded_methods = EmbeddedMethods.new(self)
embedded_methods_binding = embedded_methods.instance_eval { binding }
@@ -25,11 +32,11 @@
@master = YAML.load(data)
raise "yaml_master key is necessary on toplevel" unless @master["yaml_master"]
raise "data key is necessary on toplevel" unless @master["data"]
end
- def generate(key, output, options = {})
+ def generate(key, output = nil, options = {})
puts "gen: #{output}" if options[:verbose]
yaml = YAML.dump(fetch_data_from_master(key))
return yaml unless output
@@ -45,10 +52,27 @@
end
private
def fetch_data_from_master(key)
- @master["data"].fetch(key)
+ keys = split_key(key)
+ keys.inject(@master["data"]) do |data, k|
+ data.fetch(k)
+ end
+ rescue
+ raise KeyFetchError.new(@master["data"], key)
+ end
+
+ def split_key(key)
+ keys = key.split(".")
+ array_pattern = /\[(\d+)\]/
+ keys.map do |k|
+ if k.match(array_pattern)
+ Regexp.last_match[1].to_i
+ else
+ k
+ end
+ end
end
class EmbeddedMethods
def initialize(yaml_master)
@yaml_master = yaml_master