Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8923013
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 15, 20262026-06-15T06:59:43+00:00 2026-06-15T06:59:43+00:00

This question has been asked before: Read and write YAML files without destroying anchors

  • 0

This question has been asked before: Read and write YAML files without destroying anchors and aliases?

I was wondering how to solve that problem with many anchors and aliases?

thanks

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-15T06:59:44+00:00Added an answer on June 15, 2026 at 6:59 am

    The problem here is that anchors and aliases in Yaml are a serialization detail, and so aren’t part of the data after it’s been parsed, so the original anchor name isn’t known when writing the data back out to Yaml. In order to keep the anchor names when round tripping you need to store them somewhere when parsing so that they are available later when serializing. In Ruby any object can have instance variables associated with it, so an easy way to achieve this would be to store the anchor name in an instance variable of the objet in question.

    Continuing from the example in the earlier question, for hashes we can change our redifined revive_hash method so that if the hash is an anchor then as well as recording the anchor name in the @st variable so later alises can be recognised, we add the it as an instance variable on the hash.

    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
    

    Note that this only affects yaml mappings that are anchors. If you want to have other types to keep their anchor name you’ll need to look at psych/visitors/to_ruby.rb and make sure the name is added in all cases. Most types can be included by overriding register but there are a couple of others; search for @st.

    Now that the hash has the desired anchor name associated with it, you need to make Psych use it instead of the object id when serializing it. This can be done by subclassing YAMLTree. When YAMLTree processes an object, it first checks to see if that object has been seen already, and emits an alias for it if it has. For any new objects, it records that it has seen the object in case it needs to create an alias later. The object_id is used as the key in this, so you need to override those two methods to check for the instance variable, and use that instead if it exists:

    class MyYAMLTree < Psych::Visitors::YAMLTree
    
      # check to see if this object has been seen before
      def accept target
        if anchor_name = target.instance_variable_get('@_yaml_anchor_name')
          if @st.key? anchor_name
            oid         = anchor_name
            node        = @st[oid]
            anchor      = oid.to_s
            node.anchor = anchor
            return @emitter.alias anchor
          end
        end
    
        # accept is a pretty big method, call super to avoid copying
        # it all here. super will handle the cases when it's an object
        # that's been seen but doesn't have '@_yaml_anchor_name' set
        super
      end
    
      # record object for future, using '@_yaml_anchor_name' rather
      # than object_id if it exists
      def register target, yaml_obj
        anchor_name = target.instance_variable_get('@_yaml_anchor_name') || target.object_id
        @st[anchor_name] = yaml_obj
        yaml_obj
      end
    end
    

    Now you can use it like this (unlike the previous question, you don’t need to create a custom emitter in this case):

    builder = MyYAMLTree.new
    builder << data
    
    tree = builder.tree
    
    puts tree.yaml # returns a string
    
    # alternativelty write direct to file:
    File.open('a_file.yml', 'r+') do |f|
      tree.yaml f
    end
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I know this question has been asked before and I read all the answers
This question has been asked before but i still don't understand it fully so
This question has been asked before but the answers aren't always clear or are
This question has been asked before somewhat, but I hope mine differs. My situation
This question has been asked before perhaps multiple times, but I can't get the
My apologies if this question has been asked before. I can see there are
I know this question has been asked before however the answers I found where
I know this question has been asked before, but non of the solutions solve
I don't think this question has been asked before. I'm a bit confused on
I know this question has been asked before, and I took a look at

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.