From af6b8f78f2560cbea6baae4d0f5dd29611042b6c Mon Sep 17 00:00:00 2001 From: kwatch Date: Sat, 19 Nov 2016 08:12:00 +0900 Subject: [PATCH 1/9] feat(psych): allow to generate custom Hash object This is necessary to create custom object as mapping instead of Hash. For example, if you prefer `hashobj.key` instead of `hashobj['key']`: ## allows `h.foo` instead of `h['foo']` class MagicHash < Hash def method_missing(method, *args) return super unless args.empty? return self[method.to_s] end end ## override to generate MagicHash instead of Hash class MagicVisitor < Psych::Visitors::ToRuby def empty_mapping(o) MagicHash.new end end ## example to access `ydoc.foo` instead of `ydoc['foo']` input = <<'END' tables: - name: admin_users columns: - name: id type: int pkey: true END tree = Psych.parse(input) visitor = MagicVisitor.create ydoc = visitor.accept(tree) p ydoc.tables[0].columns[0].name #=> "name" p ydoc.tables[0].columns[0].type #=> "int" --- ext/psych/lib/psych/visitors/to_ruby.rb | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/ext/psych/lib/psych/visitors/to_ruby.rb b/ext/psych/lib/psych/visitors/to_ruby.rb index fd1c8e6..fdd1c83 100644 --- a/ext/psych/lib/psych/visitors/to_ruby.rb +++ b/ext/psych/lib/psych/visitors/to_ruby.rb @@ -159,7 +159,7 @@ def visit_Psych_Nodes_Mapping o if Psych.load_tags[o.tag] return revive(resolve_class(Psych.load_tags[o.tag]), o) end - return revive_hash(register(o, {}), o) unless o.tag + return revive_hash(register(o, empty_mapping(o)), o) unless o.tag case o.tag when /^!ruby\/struct:?(.*)?$/ @@ -320,6 +320,11 @@ def visit_Psych_Nodes_Alias o end private + + def empty_mapping o + return {} + end + def register node, object @st[node.anchor] = object if node.anchor object -- 2.9.3 (Apple Git-75)