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

Returns a new instance of LazyHash.



27
28
29
30
31
32
# File 'lib/utopia/session/lazy_hash.rb', line 27

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

Instance Attribute Details

#valuesObject (readonly)

Returns the value of attribute values.



34
35
36
# File 'lib/utopia/session/lazy_hash.rb', line 34

def values
  @values
end

Instance Method Details

#[](key) ⇒ Object



36
37
38
# File 'lib/utopia/session/lazy_hash.rb', line 36

def [] key
	load![key]
end

#[]=(key, value) ⇒ Object



40
41
42
43
44
45
46
47
48
49
# File 'lib/utopia/session/lazy_hash.rb', line 40

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

#changed?Boolean

Returns:

  • (Boolean)


63
64
65
# File 'lib/utopia/session/lazy_hash.rb', line 63

def changed?
	@changed
end

#delete(key) ⇒ Object



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

Returns:

  • (Boolean)


51
52
53
# File 'lib/utopia/session/lazy_hash.rb', line 51

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

#load!Object



67
68
69
# File 'lib/utopia/session/lazy_hash.rb', line 67

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