From ca60563c2f164308215274fe1fa393eedbe11b09 Mon Sep 17 00:00:00 2001 From: kwatch Date: Sat, 19 Nov 2016 10:41:43 +0900 Subject: [PATCH 8/9] feat(psych): support key '*' for default custom class --- ext/psych/lib/psych/visitors/custom_class.rb | 36 +++++++++++++++++++++++++++- 1 file changed, 35 insertions(+), 1 deletion(-) diff --git a/ext/psych/lib/psych/visitors/custom_class.rb b/ext/psych/lib/psych/visitors/custom_class.rb index 313e522..78eff4a 100644 --- a/ext/psych/lib/psych/visitors/custom_class.rb +++ b/ext/psych/lib/psych/visitors/custom_class.rb @@ -42,6 +42,40 @@ module Visitors ## p team.members[0].name #=> "Haruhi" ## p team.members[0].gender #=> "F" ## + ## Example2: + ## + ## ## allows `hash.foo` instead of `hash["foo"]` + ## class MagicHash < Hash + ## def method_missing(method, *args) + ## return super unless args.empty? + ## return self[method.to_s] + ## end + ## end + ## ## create visitor with MagicHash + ## require 'psych' + ## require 'psych/visitors/custom_class' + ## classmap = {'*' => MagicHash} + ## visitor = Psych::Visitors::CustomClassVisitor.create(classmap) + ## ## parse YAML document + ## input = <<-'END' + ## teams: + ## - name: SOS Brigade + ## members: + ## - {name: Haruhi, gender: F} + ## - {name: Kyon, gender: M} + ## - {name: Mikuru, gender: F} + ## - {name: Itsuki, gender: M} + ## - {name: Yuki, gender: F} + ## END + ## tree = Psych.parse(input) + ## ydoc = visitor.accept(tree) + ## p ydoc.class #=> MagicHash + ## p ydoc['teams'][0].class #=> MagicHash + ## p ydoc['teams'][0]['members'][0].class #=> MagicHash + ## p ydoc.teams[0].members[0].name #=> "Haruhi" + ## p ydoc.teams[0].members[0].gender #=> "F" + ## + class CustomClassVisitor < ToRuby def self.create(classmap={}) @@ -70,7 +104,7 @@ def accept_value(v) # pop keys end def empty_mapping(o) # generate custom object (or Hash object) - klass = @classmap[@key_path.last] + klass = @classmap[@key_path.last] || @classmap['*'] klass ? klass.new : super end -- 2.9.3 (Apple Git-75)