Why doesn't YAML.safe_load work on a YAML alias?

I have a locale file in my Rails application that works fine with Rails, but when I tried to use it with the rake task response_on_rails ( rake react_on_rails:locale), I get this error:

Psych::BadAlias: Unknown alias: item_attributes

I found that the rake task basically calls YAML.safe_load, so I prepared the simplest example without Rails, and the error still exists. Here is a sample Ruby script:

require 'yaml'

YAML.safe_load(File.open('test.yml'))

And here is the test.yml file (a shorter version of the actual locale file):

pl:
  language: Polski
  dictionary_name: simple
  activerecord:
    attributes:
      line_item: &item_attributes
        variant: Produkt
        quantity: Ilosc
        price: Cena Netto
        total_price: Wartosc Netto
        vat_rate: VAT
        total_vat_amount: Kwota VAT
        total_gross_price: Wartosc Brutto
      order_item:
        <<: *item_attributes

I still get the error:

/usr/local/Cellar/ruby/2.3.1/lib/ruby/2.3.0/psych/visitors/to_ruby.rb:402:in `visit_Psych_Nodes_Alias': Unknown alias: item_attributes (Psych::BadAlias)

Any ideas why this works fine with Rails but fails here? Any other way to avoid duplication in the YAML file and make it work for both Rails and YAML.safe_load?

+4
1

Psych, https://ruby-doc.org/stdlib-2.1.0/libdoc/psych/rdoc/Psych.html.

. :

x = []
x << x
yaml = Psych.dump x
Psych.safe_load yaml               # => raises an exception
Psych.safe_load yaml, [], [], true # => loads the aliases

, safe_load .

+6

Source: https://habr.com/ru/post/1673120/


All Articles