module Hashie::Extensions::Persistable

Opt-in YAML file persistence for classes initialized from a hash.

@example Save and reload a hash subclass

class Settings < Hash
  include Hashie::Extensions::MergeInitializer
  include Hashie::Extensions::Persistable
end
file = Tempfile.new(['hashie-example', '.yaml'], Dir.pwd)
begin
  settings = Settings.new('theme' => 'dark')
  settings.save(file.path)
  Settings.load(file.path)['theme'] # => 'dark'
ensure
  file.close!
end

Attributes

persistable_path[R]

@example Remember the last successful save location

class Settings < Hash
  include Hashie::Extensions::MergeInitializer
  include Hashie::Extensions::Persistable
end
file = Tempfile.new(['hashie-example', '.yaml'], Dir.pwd)
begin
  settings = Settings.new('theme' => 'dark')
  settings.persistable_path # => nil
  settings.save(file.path)
  settings.persistable_path # => File.expand_path(file.path)
ensure
  file.close!
end

Public Class Methods

included(base) click to toggle source
# File lib/hashie/extensions/persistable.rb, line 24
def self.included(base)
  base.extend ClassMethods
end

Public Instance Methods

save(path = persistable_path) click to toggle source

@example Save again without repeating the path

class Settings < Hash
  include Hashie::Extensions::MergeInitializer
  include Hashie::Extensions::Persistable
end
file = Tempfile.new(['hashie-example', '.yaml'], Dir.pwd)
begin
  settings = Settings.new('theme' => 'dark')
  settings.save(file.path)
  settings['theme'] = 'light'
  settings.save
  Settings.load(file.path)['theme'] # => 'light'
ensure
  file.close!
end
# File lib/hashie/extensions/persistable.rb, line 97
def save(path = persistable_path)
  raise ArgumentError, 'a persistence path is required' if path.nil?

  path = File.expand_path(File.path(path))
  yaml = Psych.dump(persistable_data(self))
  Tempfile.create(['.hashie-', '.yaml'], File.dirname(path)) do |file|
    file.chmod(File.stat(path).mode & 0o777) if File.exist?(path)
    file.write(yaml)
    file.flush
    file.fsync
    file.close
    File.rename(file.path, path)
  end
  @persistable_path = path
end

Private Instance Methods

persistable_data(value, ancestors = []) click to toggle source
# File lib/hashie/extensions/persistable.rb, line 115
def persistable_data(value, ancestors = [])
  raise ArgumentError, 'cannot persist cyclic data' if ancestors.any? { |ancestor| ancestor.equal?(value) }

  case value
  when ::Hash
    value.each_with_object({}) do |(key, child), data|
      raise TypeError, 'persisted hash keys must be strings or symbols' unless key.is_a?(String) || key.is_a?(Symbol)

      data[persistable_data(key)] = persistable_data(child, ancestors + [value])
    end
  when ::Array
    value.map { |child| persistable_data(child, ancestors + [value]) }
  when String
    value.dup
  when Symbol, Integer, Float, TrueClass, FalseClass, NilClass
    value
  else
    raise TypeError, "cannot persist a value of class `#{value.class}`"
  end
end