Search code examples
rubyyamlactivesupport

Upgrading to Ruby 3.1 causes Psych::DisallowedClass exception when using YAML.load_file


When upgrading to ruby 3.1, I am seeing the following sort error message when using YAML.load_file some_file_name

 Psych::DisallowedClass:
   Tried to load unspecified class: Matrix

Other load statements cause similar errors but cite different unspecified classes e.g. OpenStruct. It appears that the latest version of YAML only loads classes from a permitted white list, so it is necessary to use a permitted_class keyword to allow other classes. I have tried

hsh = YAML.load_file some_file_name, permitted_classes: [Matrix, OpenStruct]

but this gives the error

 Psych::DisallowedClass:
   Tried to load unspecified class: Symbol

how do I fix this?


Solution

  • Symbol is also not allowed per default when loading YAML in Ruby. Therefore, you need to add Symbol to the permitted_classes in your case too when reading the YAML file:

    hash = YAML.load_file(
      some_file_name, 
      permitted_classes: [Matrix, OpenStruct, Symbol]
    )
    

    See the list of default permitted_classes in Psych (the YAML parser used by Ruby).

    Or, when using in Ruby on Rails, you can configure globally in your config/application.rb what classes your Ruby on Rails application should allow as permitted classes when reading a YAML files:

    config.active_record.yaml_column_permitted_classes += [Matrix, OpenStruct, Symbol]
    

    Note that for internal YAML parsing in Ruby on Rails Symbol is already the default for active_record.yaml_column_permitted_classes.