dips
dips

Reputation: 380

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

I am using Ruby 2.3.0 & rails 4.2.6. I have a hash with nested array of hashes in params, and when I write it into 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 It is because the feature for serializing hash-with-ivars was added to the psych gem in its version 2.0.9. The psych gem is now a part of the Ruby standard library and this particular version of it has been added to the stdlib 2.3.0 preview1 version.

But I am trying to keep the yaml file clean by not adding any other extra params. How can I remove !ruby/hash-with-ivars: ActionController::Parameters , elements and ivars while writing into a file?

Upvotes: 4

Views: 2454

Answers (1)

Pavel Mikhailyuk
Pavel Mikhailyuk

Reputation: 2877

Actually your hash is instance of ActionController::Parameters and not Hash class. So #to_yaml stores ActionController::Parameters inner representation also.
To get plain YAML you have to convert it to Hash first.

Rails 4:

hash.to_hash.to_yaml(indentation: 8)

Rails 5 - #to_hash is deprecated, use #to_unsafe_h (returns ActiveSupport::HashWithIndifferentAccess) or #as_json instead:

hash.to_unsafe_h.to_yaml(indentation: 8)

Upvotes: 5

Related Questions