Class: Utopia::Session::LazyHash

Inherits:
Object
  • Object
show all
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

Instance Method Summary collapse

Constructor Details

#initialize(&block) ⇒ LazyHash

Initialize a lazily loaded hash.



12
13
14
15
16
17
# File 'lib/utopia/session/lazy_hash.rb', line 12

def initialize(&block)
	@changed = false
	@values = nil
	
	@loader = block
end

Instance Attribute Details

#valuesObject (readonly)

The loaded session values, if already loaded.



21
22
23
# File 'lib/utopia/session/lazy_hash.rb', line 21

def values
  @values
end

Instance Method Details

#[](key) ⇒ Object

Fetch a value by key, loading the hash if necessary.



26
27
28
# File 'lib/utopia/session/lazy_hash.rb', line 26

def [] key
	load![key]
end

#[]=(key, value) ⇒ Object

Store a value by key.



34
35
36
37
38
39
40
41
42
43
# File 'lib/utopia/session/lazy_hash.rb', line 34

def []= key, value
	values = load!
	
	if values[key] != value
		values[key] = value
		@changed = true
	end
	
	return value
end

#changed?Boolean

Check whether any value has changed.

Returns:

  • (Boolean)


65
66
67
# File 'lib/utopia/session/lazy_hash.rb', line 65

def changed?
	@changed
end

#delete(key) ⇒ Object

Delete a value by key.



55
56
57
58
59
60
61
# File 'lib/utopia/session/lazy_hash.rb', line 55

def delete(key)
	load!
	
	@changed = true if @values.include? key
	
	@values.delete(key)
end

#include?(key) ⇒ Boolean

Check whether the hash contains a key.

Returns:

  • (Boolean)


48
49
50
# File 'lib/utopia/session/lazy_hash.rb', line 48

def include?(key)
	load!.include?(key)
end

#load!Object

Load and return the underlying values.



71
72
73
# File 'lib/utopia/session/lazy_hash.rb', line 71

def load!
	@values ||= @loader.call
end

#loaded?Boolean

Check whether the underlying values have been loaded.

Returns:

  • (Boolean)


77
78
79
# File 'lib/utopia/session/lazy_hash.rb', line 77

def loaded?
	!@values.nil?
end

#needs_update?(timeout = nil) ⇒ Boolean

Check whether the values should be persisted.

Returns:

  • (Boolean)


84
85
86
87
88
89
90
91
92
93
94
95
# File 'lib/utopia/session/lazy_hash.rb', line 84

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