diff options
author | Asutosh Palai <asupalai@gmail.com> | 2016-06-09 01:18:49 +0530 |
---|---|---|
committer | Asutosh Palai <asupalai@gmail.com> | 2016-06-09 01:18:49 +0530 |
commit | 3ddce71274da2ec529685635d90cc7a208b840c9 (patch) | |
tree | 6df50a427d86404083b885adfebc12765f9c4138 /lib/bundler/yaml_serializer.rb | |
parent | 6b8fdf921e2cb0ea5fcf4c1643a9b35d06519229 (diff) | |
download | bundler-3ddce71274da2ec529685635d90cc7a208b840c9.tar.gz |
Moved the yaml serializer to seperate module
Diffstat (limited to 'lib/bundler/yaml_serializer.rb')
-rw-r--r-- | lib/bundler/yaml_serializer.rb | 46 |
1 files changed, 46 insertions, 0 deletions
diff --git a/lib/bundler/yaml_serializer.rb b/lib/bundler/yaml_serializer.rb new file mode 100644 index 0000000000..e64fe623c8 --- /dev/null +++ b/lib/bundler/yaml_serializer.rb @@ -0,0 +1,46 @@ +# frozen_string_literal: true + +module Bundler + # A stub yaml serializer that can handle only hashes and strings (as of now). + module YAMLSerializer + module_function + + def dump(hash) + yaml = String.new("---") + yaml << dump_hash(hash) + end + + def dump_hash(hash) + yaml = String.new("\n") + hash.each do |k, v| + yaml << k << ":" + if v.is_a?(Hash) + yaml << dump_hash(v).gsub(/^(?!$)/, " ") # indent all non-empty lines + else + yaml << " " << v.to_s.gsub(/\s+/, " ").inspect << "\n" + end + end + yaml + end + + def load(str) + res = {} + stack = [res] + str.scan(/^( *)(.*):\s?(["']?)([^"'\n]*)\3\n/).each do |(indent, key, _, val)| + depth = indent.scan(/ /).length + if val.empty? + new_hash = {} + stack[depth][key] = new_hash + stack[depth + 1] = new_hash + else + stack[depth][key] = val + end + end + res + end + + class << self + private :dump_hash + end + end +end |