Class: Storage

Inherits:
Object
  • Object
show all
Defined in:
lib/simple_gui_creator/storage.rb

Class Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(name) ⇒ Storage

Open a storage file or create it if it doesn’t exist.

Parameters:

  • a (String)

    (short) name, should be suitable for use as a filename



34
35
36
37
38
39
40
41
# File 'lib/simple_gui_creator/storage.rb', line 34

def initialize(name)
  @name    = name
  unless File.exists?(Storage.storage_dir)
		  require 'fileutils'
    FileUtils.mkdir_p(Storage.storage_dir)
  end
  rollback
end

Class Attribute Details

.storage_dirObject



27
28
29
# File 'lib/simple_gui_creator/storage.rb', line 27

def self.storage_dir
  @user_dir ||= File.join(File.expand_path('~'), ".sensible_cinema_storage")
end

Instance Method Details

#[](key) ⇒ Object

retrieve key value note: it does not re-read from disk before returning you this value



81
82
83
84
85
86
87
88
# File 'lib/simple_gui_creator/storage.rb', line 81

def [](key)
  if @last_modified_time
    if File.exist?(path()) && (File.stat(path()).mtime != @last_modified_time)
      rollback
    end
  end
  @storage[key]
end

#[]=(key, value) ⇒ Object

set key to value note: it automatically saves this to disk



92
93
94
95
96
# File 'lib/simple_gui_creator/storage.rb', line 92

def []=(key, value)
  @storage[key] = value
  save
  value
end

#clear!Object



50
51
52
53
54
55
56
57
58
59
# File 'lib/simple_gui_creator/storage.rb', line 50

def clear!
   @storage = {}
   begin
    File.delete path
   rescue => e
     if File.exist? path
      raise
     end
   end
end

#keysObject



111
112
113
# File 'lib/simple_gui_creator/storage.rb', line 111

def keys
  @storage.keys
end

#rollbackObject

Rollback the storage to the latest revision saved to disk or empty it if it hasn’t been saved.



63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
# File 'lib/simple_gui_creator/storage.rb', line 63

def rollback
  if File.exists?(path)
    @storage = YAML.load_file(path)
    unless @storage.is_a? Hash
      
      $stderr.puts 'storage file is corrupted--deleting ' + path
      clear!
   
    end
    update_timestamp
  else
    @storage = {}
  end
  self
end

#saveObject

Save the storage to disk.



44
45
46
47
48
# File 'lib/simple_gui_creator/storage.rb', line 44

def save
				File.open(path, "w") { |f| YAML.dump(@storage, f) }
  update_timestamp
  self
end

#set_default(key, value) ⇒ Object



98
99
100
101
102
103
# File 'lib/simple_gui_creator/storage.rb', line 98

def set_default(key, value)
  unless @storage.has_key?(key)
    self[key] = value
  end
  value
end

#set_once(key) ⇒ Object



105
106
107
108
109
# File 'lib/simple_gui_creator/storage.rb', line 105

def set_once key
  unless @storage.has_key?(key)
 self[key] = yield
		end
end