1

I'm making dynamic yaml file in Ruby

I have following hash

{
  "defaults"=>
          {"foo"=>"bar", "zip"=>"button"},
           "node"=>
                  {
                   "<<"=>
                  {"foo"=>"bar", "zip"=>"button"}, 
                   "foo"=>"other"
                   }
}

when i try to parse it using

tree = Psych.parse your_data
data = ToRubyNoMerge.new.accept tree

having parser functions override like here

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

Now when i try

tree = Psych.dump yaml_constants
data = ToRubyNoMerge.new.accept tree
File.open(file, 'w') { |f| YAML.dump(data.to_yaml, f) }

It give me below error

psych/visitors/to_ruby.rb:23:in `initialize': wrong number of arguments (given 0, expected 2) (ArgumentError)

we can see that it makes sense , because revive_hash is taking two arguments but the same thing worked for This guys . can anyone tell me what i'm doing wrong

Note: I'm following This Post for parsing and asked @matt for this issue but he's not responsing

Community
  • 1
  • 1
Mani
  • 2,391
  • 5
  • 37
  • 81

1 Answers1

0

we can see that it makes sense, because revive_hash is taking two arguments

The error you are getting has nothing to do with revive_hash.

As one might read in the documentation, Psych::Visitors::ToRuby#new expects two params: ClassLoader and ScalarScanner.

You instantiate ToRubyMerge, which is a direct descendant of the above, providing no parameters to initialize at all. This is exactly what the error you get is saying.

To use defaults for both one might use #create factory:

#             ⇓⇓⇓⇓⇓⇓
ToRubyNoMerge.create.accept tree
Aleksei Matiushkin
  • 119,336
  • 10
  • 100
  • 160
  • dear i made the change and now it says - undefined method `visit_String' for #< ToRubyNoMerge . – Mani Jul 08 '16 at 07:35
  • This is completely unrelated to the original question. – Aleksei Matiushkin Jul 08 '16 at 08:06
  • i also think so , okay i check for this error and then i'll check for your answer too .. i just thought it worth to ask - thanks again . but if you have any info about it kindly lemme know – Mani Jul 08 '16 at 08:19