开发者

Which are the equivalents of the Marshal methods _load and _dump in Ruby YAML?

开发者 https://www.devze.com 2023-03-28 21:45 出处:网络
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

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
   开发者_C百科 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


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.

require 'yaml'
class Foo
  def initialize(numbers)
    @numbers = numbers
  end

  def to_yaml
    Yaml::dump(self)
  end

  def self.from_yaml(dump)
    Yaml::load(dump)
  end
end


http://corelib.rubyonrails.org/classes/YAML.html

require "yaml"

test_obj = ["dogs", "cats", "badgers"]

yaml_obj = YAML::dump( test_obj )
                    # -> ---
                         - dogs
                         - cats
                         - badgers
ruby_obj = YAML::load( yaml_obj )
                    # => ["dogs", "cats", "badgers"]
ruby_obj == test_obj
                    # => true


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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号