Class: Utopia::Session::LazyHash
- Inherits:
-
Object
- Object
- Utopia::Session::LazyHash
- Defined in:
- lib/utopia/session/lazy_hash.rb
Overview
A simple hash table which fetches it’s values only when required.
Instance Attribute Summary collapse
-
#values ⇒ Object
readonly
Returns the value of attribute values.
Instance Method Summary collapse
-
#[](key) ⇒ Object
-
#[]=(key, value) ⇒ Object
-
#changed? ⇒ Boolean
-
#delete(key) ⇒ Object
-
#include?(key) ⇒ Boolean
-
#initialize(&block) ⇒ LazyHash
constructor
A new instance of LazyHash.
-
#load! ⇒ Object
-
#loaded? ⇒ Boolean
-
#needs_update?(timeout = nil) ⇒ Boolean
Constructor Details
#initialize(&block) ⇒ LazyHash
Returns a new instance of LazyHash
25 26 27 28 29 30 |
# File 'lib/utopia/session/lazy_hash.rb', line 25 def initialize(&block) @changed = false @values = nil @loader = block end |
Instance Attribute Details
#values ⇒ Object (readonly)
Returns the value of attribute values
32 33 34 |
# File 'lib/utopia/session/lazy_hash.rb', line 32 def values @values end |
Instance Method Details
#[](key) ⇒ Object
34 35 36 |
# File 'lib/utopia/session/lazy_hash.rb', line 34 def [] key load![key] end |
#[]=(key, value) ⇒ Object
38 39 40 41 42 43 44 45 46 47 |
# File 'lib/utopia/session/lazy_hash.rb', line 38 def []= key, value values = load! if values[key] != value values[key] = value @changed = true end return value end |
#changed? ⇒ Boolean
61 62 63 |
# File 'lib/utopia/session/lazy_hash.rb', line 61 def changed? @changed end |
#delete(key) ⇒ Object
53 54 55 56 57 58 59 |
# File 'lib/utopia/session/lazy_hash.rb', line 53 def delete(key) load! @changed = true if @values.include? key @values.delete(key) end |
#include?(key) ⇒ Boolean
49 50 51 |
# File 'lib/utopia/session/lazy_hash.rb', line 49 def include?(key) load!.include?(key) end |
#load! ⇒ Object
65 66 67 |
# File 'lib/utopia/session/lazy_hash.rb', line 65 def load! @values ||= @loader.call end |
#loaded? ⇒ Boolean
69 70 71 |
# File 'lib/utopia/session/lazy_hash.rb', line 69 def loaded? !@values.nil? end |
#needs_update?(timeout = nil) ⇒ Boolean
73 74 75 76 77 78 79 80 81 82 83 84 |
# File 'lib/utopia/session/lazy_hash.rb', line 73 def needs_update?(timeout = nil) # If data has changed, we need update: return true if @changed # We want to be careful here and not call load! which isn't cheap operation. if timeout and @values and updated_at = @values[:updated_at] # If the last update was too long ago, we need update: return true if updated_at < (Time.now - timeout) end return false end |