Class: LapisLazuli::Storage
- Inherits:
-
Object
- Object
- LapisLazuli::Storage
- Defined in:
- lib/lapis_lazuli/storage.rb
Overview
Simple storage class
Instance Method Summary collapse
-
#destroy(world) ⇒ Object
This will be called during the destruction of the world.
- #get(key) ⇒ Object
- #has?(key) ⇒ Boolean
-
#initialize(name = nil) ⇒ Storage
constructor
Initialize the storage with an optional name.
- #set(key, value) ⇒ Object
-
#writeToFile(filename = nil) ⇒ Object
Write all stored data to file.
Constructor Details
#initialize(name = nil) ⇒ Storage
Initialize the storage with an optional name
18 19 20 21 |
# File 'lib/lapis_lazuli/storage.rb', line 18 def initialize(name=nil) @name = name @data = {} end |
Instance Method Details
#destroy(world) ⇒ Object
This will be called during the destruction of the world
62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 |
# File 'lib/lapis_lazuli/storage.rb', line 62 def destroy(world) # No data to write if @data.keys.length == 0 world.log.debug("Storage '#{@name}' is empty") return end filename = nil # If we have a name if !@name.nil? # Check the environment for a filename env_value = world.env("#{@name}_file", nil) if !env_value.nil? filename = env_value end end # Otherwise, generate a name if filename.nil? # Folder to store in filename = world.config("storage_dir", ".#{File::SEPARATOR}storage") + File::SEPARATOR # Filename if @name.nil? # Use current timestamp and the object_id of the data filename += world.time[:timestamp] + "_" + @data.object_id else # Use the given name filename += @name end # JSON file extension filename += ".json" end world.log.debug("Writing storage to: #{filename}") self.writeToFile(filename) end |
#get(key) ⇒ Object
27 28 29 |
# File 'lib/lapis_lazuli/storage.rb', line 27 def get(key) return @data[key] end |
#has?(key) ⇒ Boolean
31 32 33 |
# File 'lib/lapis_lazuli/storage.rb', line 31 def has?(key) return @data.include? key end |
#set(key, value) ⇒ Object
23 24 25 |
# File 'lib/lapis_lazuli/storage.rb', line 23 def set(key, value) @data[key] = value end |
#writeToFile(filename = nil) ⇒ Object
Write all stored data to file
37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 |
# File 'lib/lapis_lazuli/storage.rb', line 37 def writeToFile(filename=nil) if filename.nil? && @name.nil? raise "Need a filename" elsif filename.nil? filename = "#{@name}.json" end # Make storage directory dir = File.dirname(filename) begin Dir.mkdir dir rescue SystemCallError => ex # Swallow this error; it occurs (amongst other situations) when the # directory exists. Checking for an existing directory beforehand is # not concurrency safe. end File.open(filename, 'w') { |file| # Write the JSON to the file file.puts(@data.to_json) } end |