1 28 package org.jruby.yaml; 29 30 import java.io.IOException ; 31 32 import org.jruby.RubyArray; 33 import org.jruby.RubyHash; 34 35 import org.jruby.runtime.builtin.IRubyObject; 36 37 import org.jruby.javasupport.JavaEmbedUtils; 38 39 import org.jvyamlb.SafeRepresenterImpl; 40 import org.jvyamlb.Serializer; 41 import org.jvyamlb.Representer; 42 import org.jvyamlb.YAMLConfig; 43 import org.jvyamlb.YAMLNodeCreator; 44 import org.jvyamlb.nodes.Node; 45 46 import org.jruby.util.ByteList; 47 48 51 public class JRubyRepresenter extends SafeRepresenterImpl { 52 public JRubyRepresenter(final Serializer serializer, final YAMLConfig opts) { 53 super(serializer,opts); 54 } 55 56 protected YAMLNodeCreator getNodeCreatorFor(final Object data) { 57 if(data instanceof YAMLNodeCreator) { 58 return (YAMLNodeCreator)data; 59 } else if(data instanceof IRubyObject) { 60 return new IRubyObjectYAMLNodeCreator(data); 61 } else { 62 return super.getNodeCreatorFor(data); 63 } 64 } 65 66 public Node map(String tag, java.util.Map mapping, Object flowStyle) throws IOException { 67 if(mapping instanceof RubyHash) { 68 mapping = ((RubyHash)mapping).getValueMap(); 69 } 70 if(null == flowStyle) { 71 return map(tag,mapping,false); 72 } else { 73 return map(tag,mapping,true); 74 } 75 } 76 public Node seq(String tag, java.util.List sequence, Object flowStyle) throws IOException { 77 if(sequence instanceof RubyArray) { 78 sequence = ((RubyArray)sequence).getList(); 79 } 80 81 if(null == flowStyle) { 82 return seq(tag,sequence,false); 83 } else { 84 return seq(tag,sequence,true); 85 } 86 } 87 88 public Node scalar(String tag, String val, String style) throws IOException { 89 return scalar(tag, ByteList.create(val), style); 90 } 91 92 public Node scalar(String tag, ByteList val, String style) throws IOException { 93 if(null == style || style.length() == 0) { 94 return scalar(tag,val,(char)0); 95 } else { 96 return scalar(tag,val,style.charAt(0)); 97 } 98 } 99 100 protected boolean ignoreAliases(final Object data) { 101 return (data instanceof IRubyObject && ((IRubyObject)data).isNil()) || super.ignoreAliases(data); 102 } 103 104 public static class IRubyObjectYAMLNodeCreator implements YAMLNodeCreator { 105 private final IRubyObject data; 106 107 public IRubyObjectYAMLNodeCreator(final Object data) { 108 this.data = (IRubyObject)data; 109 } 110 111 public String taguri() { 112 return data.callMethod(data.getRuntime().getCurrentContext(), "taguri").toString(); 113 } 114 115 public Node toYamlNode(final Representer representer) throws IOException { 116 Object val = data.callMethod(data.getRuntime().getCurrentContext(), "to_yaml_node", JavaEmbedUtils.javaToRuby(data.getRuntime(),representer)); 117 if(val instanceof Node) { 118 return (Node)val; 119 } else if(val instanceof IRubyObject) { 120 return (Node)JavaEmbedUtils.rubyToJava(data.getRuntime(),(IRubyObject)val,Node.class); 121 } 122 return null; 123 } 124 } 125 } | Popular Tags |