Can "! Ruby / hash: ActionController :: Parameters" be removed when object.to_yaml (YAML) is in ruby ​​on rails?

I am using Ruby 2.3.0 and rails 4.2.6. I have a hash with a nested array of hashes in params and when I write it to a file

hash = {"abc"=> [{"abc1"=>[{"key1" => value1},{"key2" => value2}]}]}

File.open("abc.yaml",'w+') {|f| f.write hash.to_yaml(:indentation => 8) }

      

abc.yaml

 ---
 abc:
 - !ruby/hash-with-ivars:ActionController::Parameters
    elements:
            abc1: &2
            - !ruby/hash-with-ivars:ActionController::Parameters
                    elements:
                            key1: value1
                            key2: value2
                    ivars:
                            :@permitted: false
            - !ruby/hash-with-ivars:ActionController::Parameters
                    elements:
                            key1: value1
                            key2: value2
                    ivars:
                            :@permitted: false
    ivars:
            :@permitted: false
            :@converted_arrays: !ruby/object:Set
                    hash:
                            *2: true

      

Its mentioned here This is because a function to serialize hashs with ivars was added to psych stone in version 2.0.9. Psychic Stone is now part of the Ruby standard library and this particular version was added in stdlib 2.3.0 preview1.

But I am trying to keep the yaml file clean without adding any other additional parameters. How can I remove ruby ​​/ hash-with-ivars: ActionController :: Parameters, items and ivars when writing to a file?

+3


source to share


1 answer


Actually yours hash

is an instance of the class ActionController::Parameters

, not hash

. So, it #to_yaml

stores an internal representation ActionController::Parameters

.
To get simple YAML, you must first convert it to hash

.

Rails 4 :

hash.to_hash.to_yaml(indentation: 8)

      



Rails 5 is #to_hash

deprecated, use #to_unsafe_h

(returns ActiveSupport::HashWithIndifferentAccess

) or #as_json

instead:

hash.to_unsafe_h.to_yaml(indentation: 8)

      

+3


source







All Articles