我在 Ruby
制作动态 yaml file
我有以下哈希
{
"defaults"=>
{"foo"=>"bar", "zip"=>"button"},
"node"=>
{
"<<"=>
{"foo"=>"bar", "zip"=>"button"},
"foo"=>"other"
}
}
当我尝试使用解析它
tree = Psych.parse your_data
data = ToRubyNoMerge.new.accept tree
让解析器函数像这里一样覆盖
require 'psych'
class ToRubyNoMerge < Psych::Visitors::ToRuby
def revive_hash hash, o
if o.anchor
@st[o.anchor] = hash
hash.instance_variable_set "@_yaml_anchor_name", o.anchor
end
o.children.each_slice(2) { |k,v|
key = accept(k)
hash[key] = accept(v)
}
hash
end
end
class MyEmitter < Psych::Visitors::Emitter
def visit_Psych_Nodes_Mapping o
o.anchor = 'defaults' if o.anchor
super
end
def visit_Psych_Nodes_Alias o
o.anchor = 'defaults' if o.anchor
super
end
end
现在,当我尝试
tree = Psych.dump yaml_constants
data = ToRubyNoMerge.new.accept tree
File.open(file, 'w') { |f| YAML.dump(data.to_yaml, f) }
它给我下面 error
psych / visitor / to_ruby.rb:23:在`initialize'中:参数个数错误(给定0,预期2)(ArgumentError)
我们可以看到它是有道理的,因为 revive_hash
正在采取两个论点,但同样的事情适用于This伙伴们 . 任何人都可以告诉我我做错了什么
注意:我正在关注This Post for parsing并向@matt询问此问题,但他没有回应
1 回答
你得到的错误与
revive_hash
无关 .正如人们可能在文档中读到的那样,Psych::Visitors::ToRuby#new期望两个参数:
ClassLoader
和ScalarScanner
.您实例化
ToRubyMerge
,它是上述的直接后代,根本不为initialize
提供任何参数 . 这正是你得到的错误所说的 .要使用两者的默认值,可以使用#create factory: