1#
2# YAML::Store
3#
4require 'yaml'
5require 'pstore'
6
7# YAML::Store provides the same functionality as PStore, except it uses YAML
8# to dump objects instead of Marshal.
9#
10# == Example
11#
12#   require 'yaml/store'
13#
14#   Person = Struct.new :first_name, :last_name
15#
16#   people = [Person.new("Bob", "Smith"), Person.new("Mary", "Johnson")]
17#
18#   store = YAML::Store.new "test.store"
19#
20#   store.transaction do
21#     store["people"] = people
22#     store["greeting"] = { "hello" => "world" }
23#   end
24#
25# After running the above code, the contents of "test.store" will be:
26#
27#   ---
28#   people:
29#   - !ruby/struct:Person
30#     first_name: Bob
31#     last_name: Smith
32#   - !ruby/struct:Person
33#     first_name: Mary
34#     last_name: Johnson
35#   greeting:
36#     hello: world
37
38class YAML::Store < PStore
39
40  # :call-seq:
41  #   initialize( file_name, yaml_opts = {} )
42  #
43  # Creates a new YAML::Store object, which will store data in +file_name+.
44  # If the file does not already exist, it will be created.
45  #
46  #
47  # Options passed in through +yaml_opts+ will be used when converting the
48  # store to YAML via Hash#to_yaml().
49  def initialize file_name, yaml_opts = {}
50    @opt = yaml_opts
51    super
52  end
53
54  # :stopdoc:
55
56  def dump(table)
57    YAML.dump @table
58  end
59
60  def load(content)
61    table = YAML.load(content)
62    if table == false
63      {}
64    else
65      table
66    end
67  end
68
69  def marshal_dump_supports_canonical_option?
70    false
71  end
72
73  EMPTY_MARSHAL_DATA = YAML.dump({})
74  EMPTY_MARSHAL_CHECKSUM = Digest::MD5.digest(EMPTY_MARSHAL_DATA)
75  def empty_marshal_data
76    EMPTY_MARSHAL_DATA
77  end
78  def empty_marshal_checksum
79    EMPTY_MARSHAL_CHECKSUM
80  end
81end
82