Class: StoredHash
- Inherits:
-
Object
- Object
- StoredHash
- Defined in:
- lib/stored_hash.rb
Overview
This is a drop in replacement for Hash. It does act just the same but reads/writes from a yaml file whenever the hash or the file changes. This is much slower than a hash, as you might guess. A StoredHash is thread-safe.
Instance Attribute Summary collapse
-
#file ⇒ Object
readonly
Returns the value of attribute file.
Instance Method Summary collapse
- #==(other) ⇒ Object
-
#initialize(file, *args, &block) ⇒ StoredHash
constructor
A new instance of StoredHash.
- #is_a?(whatever) ⇒ Boolean
-
#method_missing(*args, &blk) ⇒ Object
Here is where the magic happens.
- #to_hash ⇒ Object
Constructor Details
#initialize(file, *args, &block) ⇒ StoredHash
Returns a new instance of StoredHash.
17 18 19 20 21 |
# File 'lib/stored_hash.rb', line 17 def initialize file, *args, &block @data = Hash.new(*args, &block) @file = file @mutex = Mutex.new end |
Dynamic Method Handling
This class handles dynamic methods through the method_missing method
#method_missing(*args, &blk) ⇒ Object
Here is where the magic happens. Before any method is called on the hash we’ll check the file for changes (of course only reading the file if it has been changed). After the method terminated we check whether the hash has been changed and if so, we write it to the file.
49 50 51 52 53 54 55 56 57 58 |
# File 'lib/stored_hash.rb', line 49 def method_missing(*args, &blk) synchronize do |file| update file if should_update? file @old_data ||= duplicate_data result = @data.send(*args, &blk) write if should_write? return self if result == @data result end end |
Instance Attribute Details
#file ⇒ Object (readonly)
Returns the value of attribute file.
11 12 13 |
# File 'lib/stored_hash.rb', line 11 def file @file end |
Instance Method Details
#==(other) ⇒ Object
23 24 25 |
# File 'lib/stored_hash.rb', line 23 def == other super or @data == other end |
#is_a?(whatever) ⇒ Boolean
64 65 66 |
# File 'lib/stored_hash.rb', line 64 def is_a? whatever super whatever or @data.is_a? whatever end |
#to_hash ⇒ Object
60 61 62 |
# File 'lib/stored_hash.rb', line 60 def to_hash @data.dup end |