Skip to content
Browse files

represent scalar works

  • Loading branch information...
1 parent 35ca1ca commit 182f450bd8b60a1b615db517e54d74c8a836e2a1 @tenderlove committed Feb 2, 2010
Showing with 49 additions and 1 deletion.
  1. +6 −0 lib/psych/coder.rb
  2. +12 −0 lib/psych/visitors/to_ruby.rb
  3. +1 −1 lib/psych/visitors/yaml_tree.rb
  4. +30 −0 test/psych/test_coder.rb
View
6 lib/psych/coder.rb
@@ -19,6 +19,12 @@ def initialize tag
@scalar = nil
end
+ # Emit a scalar with +value+ and +tag+
+ def represent_scalar tag, value
+ self.tag = tag
+ self.scalar = value
+ end
+
# Emit a scalar with +value+
def scalar= value
@type = :scalar
View
12 lib/psych/visitors/to_ruby.rb
@@ -28,6 +28,18 @@ def accept target
def visit_Psych_Nodes_Scalar o
@st[o.anchor] = o.value if o.anchor
+ if klass = Psych.load_tags[o.tag]
+ instance = klass.allocate
+
+ if instance.respond_to?(:init_with)
+ coder = Psych::Coder.new(o.tag)
+ coder.scalar = o.value
+ instance.init_with coder
+ end
+
+ return instance
+ end
+
return o.value if o.quoted
return @ss.tokenize(o.value) unless o.tag
View
2 lib/psych/visitors/yaml_tree.rb
@@ -255,7 +255,7 @@ def dump_coder o
def emit_coder c
case c.type
when :scalar
- append Nodes::Scalar.new(c.scalar, nil, c.tag)
+ append Nodes::Scalar.new(c.scalar, nil, c.tag, c.tag.nil?)
when :map
map = append Nodes::Mapping.new(nil, c.tag, c.implicit, c.style)
@stack.push map
View
30 test/psych/test_coder.rb
@@ -44,6 +44,36 @@ def encode_with coder
end
end
+ class Represent
+ yaml_tag 'foo'
+ def encode_with coder
+ coder.represent_scalar 'foo', 'bar'
+ end
+ end
+
+ class RepresentWithInit
+ yaml_tag name
+ attr_accessor :str
+
+ def init_with coder
+ @str = coder.scalar
+ end
+
+ def encode_with coder
+ coder.represent_scalar self.class.name, 'bar'
+ end
+ end
+
+ def test_represent_with_init
+ thing = Psych.load(Psych.dump(RepresentWithInit.new))
+ assert_equal 'bar', thing.str
+ end
+
+ def test_represent!
+ assert_match(/foo/, Psych.dump(Represent.new))
+ assert_instance_of(Represent, Psych.load(Psych.dump(Represent.new)))
+ end
+
def test_scalar_coder
foo = Psych.load(Psych.dump(ScalarCoder.new))
assert_equal 'foo', foo

0 comments on commit 182f450

Please sign in to comment.
Something went wrong with that request. Please try again.