Class: Blur::Script::Cache

Inherits:
Object
  • Object
show all
Defined in:
library/blur/script/cache.rb

Overview

The Cache class enables data storing inside Blur and it scripts.

What it does is simply store a hash, and act like it is that hash.

When the client closes, it sends a message to all available scripts and then those scripts tells the cache to save, in order to remember that data and reload it at the next run.

Cache can then save the contents of the hash to a yaml file that persists in the ./cache/ directory.

That same file is then loaded once needed again.

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(script) ⇒ Cache

Instantiate a cache with a script reference.



35
36
37
38
# File 'library/blur/script/cache.rb', line 35

def initialize script
  @hash   = {}
  @script = script
end

Class Method Details

.exists?(name) ⇒ Boolean

Check if there exists a cache file for the script with name name.



24
25
26
# File 'library/blur/script/cache.rb', line 24

def self.exists? name
  File.exists? "#{path}/#{name}.yml"
end

.pathObject

Get the path to the cache directory (./cache/)



19
20
21
# File 'library/blur/script/cache.rb', line 19

def self.path
  %{#{File.dirname File.expand_path $0}/cache}
end

Instance Method Details

#[](key) ⇒ Object

Get a cache value by key.



29
# File 'library/blur/script/cache.rb', line 29

def [] key; @hash[key] end

#[]=(key, value) ⇒ Object

Set a cache value by key.



32
# File 'library/blur/script/cache.rb', line 32

def []= key, value; @hash[key] = value end

#loadHash

Load a yaml file as internal data from the cache directory.



56
57
58
59
60
61
62
# File 'library/blur/script/cache.rb', line 56

def load
  if yaml = YAML.load_file(path)
    @hash = yaml
  end
rescue
  File.unlink path
end

#saveObject

Save all internal data to a yaml file in the cache directory.



41
42
43
44
45
46
47
48
49
50
51
# File 'library/blur/script/cache.rb', line 41

def save
  directory = File.dirname path
  
  unless File.directory? directory
    Dir.mkdir directory
  end
  
  File.open path, ?w do |file|
    YAML.dump @hash, file
  end
end

#to_sObject

Let Hash#to_s do the job.



65
# File 'library/blur/script/cache.rb', line 65

def to_s; @hash end