Skip to content

Instantly share code, notes, and snippets.

@taichi-ishitani
Created August 20, 2019 07:51
Show Gist options
  • Save taichi-ishitani/5938facd74a33f2204b23b6728e0d431 to your computer and use it in GitHub Desktop.
Save taichi-ishitani/5938facd74a33f2204b23b6728e0d431 to your computer and use it in GitHub Desktop.
[YAML] load with location info
require 'yaml'
src = <<~YAML
name: taro
age: 4
YAML
class Psych::Nodes::Node
def mapping_key?
@mapping_key
end
attr_writer :mapping_key
end
class MyTreeBuilder < Psych::TreeBuilder
def scalar(value, anchor, tag, plain, quoted, style)
node = super
if @last.mapping? && @last.children.size.odd?
node.mapping_key = true
end
node
end
end
class MyToRubyVisitor < Psych::Visitors::ToRuby
def register(node, object)
if node.scalar? && !node.mapping_key?
object = [object, [node.start_line, node.start_column]]
end
super(node, object)
end
end
parser = Psych::Parser.new
handler = MyTreeBuilder.new
parser.handler = handler
parser.parse(src)
result = parser.handler.root.children[0]
visitor = MyToRubyVisitor.create
object = visitor.accept(result)
p object # => {"name"=>["taro", [0, 6]], "age"=>[4, [1, 5]]}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment