哪些与 Ruby YAML 中的 Marshal 方法 _load 和 _dump 等效?
我正在使用标准 YAML 库,我有一个对象,在转储时将其转换为哈希,并在加载时从哈希转换。在 Marshal 中,我使用了 _load 和 _dump 方法重载,但 Marshal 不是人类可读的 =/
我想要自动加载对象的东西,比如 Marshal =/
类似这样的东西:
class Foo
def initialize(numbers)
@numbers = numbers
end
def to_yaml
dump = {}
@numbers.each {|k, v| dump[k.to_s] = v.to_s}
dump.to_yaml
end
def self.from_yaml(dump)
dump = YAML.load(dump)
numbers = {}
dump.each {|k, v| numbers[k.to_sym] = v.to_sym}
new(numbers)
end
end
bar = Foo.new({:one => :uno, :two => :dos, :three => :tres})
bar_yaml = bar.to_yaml
var = Foo.from_yaml(bar_yaml)
p var
但不太明确
I'm using the standard YAML library, I have an object that I convert to a hash when dumping it, and I convert from a hash when loading. In Marshal I used _load and _dump methods overload, but Marshal is not human-readable =/
I want something that load automatically the objects, like Marshal =/
Something like this:
class Foo
def initialize(numbers)
@numbers = numbers
end
def to_yaml
dump = {}
@numbers.each {|k, v| dump[k.to_s] = v.to_s}
dump.to_yaml
end
def self.from_yaml(dump)
dump = YAML.load(dump)
numbers = {}
dump.each {|k, v| numbers[k.to_sym] = v.to_sym}
new(numbers)
end
end
bar = Foo.new({:one => :uno, :two => :dos, :three => :tres})
bar_yaml = bar.to_yaml
var = Foo.from_yaml(bar_yaml)
p var
But less explicit
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
除非我遗漏了你问题的某些部分,否则包装上面推荐的 juwiley 方法似乎是一个非常简单的解决方案。
Unless I'm missing some part of your question, it seems like wrapping the methods that juwiley recommended above would be a very simple solution.
http://corelib.rubyonrails.org/classes/YAML.html
http://corelib.rubyonrails.org/classes/YAML.html
在这种情况下,您可以查看 Rails ActiveRecord 序列化功能
http://api.rubyonrails。 org/classes/ActiveRecord/Base.html
我假设您想在保存后将 YAML 持久保存到数据库
In that case you might take a look at Rails ActiveRecord serialize functionality
http://api.rubyonrails.org/classes/ActiveRecord/Base.html
I'm assuming you want to persist the YAML to DB after save