about summary refs log tree commit homepage
path: root/lib/dtas/state_file.rb
blob: b6f36179170e10d593baae8aac75504f0c9758ad (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
# -*- encoding: binary -*-
# Copyright (C) 2013, Eric Wong <normalperson@yhbt.net>
# License: GPLv3 or later (https://www.gnu.org/licenses/gpl-3.0.txt)
require 'yaml'
require 'tempfile'
class DTAS::StateFile # :nodoc:
  def initialize(path, do_fsync = false)
    @path = path
    @do_fsync = do_fsync
  end

  def tryload
    YAML.load(IO.binread(@path)) if File.readable?(@path)
  end

  def dump(obj, force_fsync = false)
    yaml = obj.to_hsh.to_yaml.b

    # do not replace existing state file if there are no changes
    # this will be racy if we ever do async dumps or shared state
    # files, but we don't do that...
    return if File.readable?(@path) && IO.binread(@path) == yaml

    dir = File.dirname(@path)
    Tempfile.open(%w(player.state .tmp), dir) do |tmp|
      tmp.binmode
      tmp.write(yaml)
      tmp.flush
      tmp.fsync if @do_fsync || force_fsync
      File.rename(tmp.path, @path)
    end
  end
end