[英]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. 我使用的是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 我有一个哈希,在params中有嵌套的哈希数组,当我把它写入文件时
hash = {"abc"=> [{"abc1"=>[{"key1" => value1},{"key2" => value2}]}]}
File.open("abc.yaml",'w+') {|f| f.write hash.to_yaml(:indentation => 8) }
abc.yaml 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. 它在这里提到这是因为序列化hash-with-ivars的功能被添加到版本2.0.9中的psych gem。 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. psych gem现在是Ruby标准库的一部分,它的特定版本已添加到stdlib 2.3.0 preview1版本中。
But I am trying to keep the yaml file clean by not adding any other extra params. 但我试图通过不添加任何其他额外的参数保持yaml文件清洁。 How can I remove !ruby/hash-with-ivars: ActionController::Parameters , elements and ivars while writing into a file? 如何删除!ruby / hash-with-ivars:ActionController ::写入文件时的参数,元素和ivars?
Actually your hash
is instance of ActionController::Parameters
and not Hash
class. 实际上你的hash
是ActionController::Parameters
实例,而不是Hash
类。 So #to_yaml
stores ActionController::Parameters
inner representation also. 所以#to_yaml
存储了ActionController::Parameters
内部表示。
To get plain YAML you have to convert it to Hash
first. 要获得简单的YAML,您必须先将其转换为Hash
。
Rails 4 : 导轨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: Rails 5 - #to_hash
已弃用,请使用#to_unsafe_h
(返回ActiveSupport::HashWithIndifferentAccess
)或#as_json
:
hash.to_unsafe_h.to_yaml(indentation: 8)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.