Class: Volt::Persistors::Cookies
- Inherits:
-
Base
show all
- Defined in:
- lib/volt/models/persistors/cookies.rb
Overview
Backs a collection in the local store
Instance Method Summary
collapse
Methods inherited from Base
#event_added, #event_removed
Constructor Details
#initialize(model) ⇒ Cookies
Returns a new instance of Cookies.
44
45
46
|
# File 'lib/volt/models/persistors/cookies.rb', line 44
def initialize(model)
@model = model
end
|
Instance Method Details
#added(model, index) ⇒ Object
Called when a model is added to the collection
49
50
51
|
# File 'lib/volt/models/persistors/cookies.rb', line 49
def added(model, index)
end
|
#changed(attribute_name) ⇒ Object
Callled when an cookies value is changed
68
69
70
71
72
73
74
75
76
|
# File 'lib/volt/models/persistors/cookies.rb', line 68
def changed(attribute_name)
unless $writing_cookies
value = @model.read_attribute(attribute_name)
write_cookie(attribute_name, value.to_s, expires: Time.now + (356 * 24 * 60 * 60))
end
end
|
#loaded(initial_state = nil) ⇒ Object
53
54
55
56
57
58
59
60
61
62
63
64
65
|
# File 'lib/volt/models/persistors/cookies.rb', line 53
def loaded(initial_state = nil)
if !@loaded && @model.path == []
@loaded = true
writing_cookies do
read_cookies.each_pair do |key, value|
@model.assign_attribute(key, value)
end
end
end
end
|
#read_cookies ⇒ Object
10
11
12
13
14
15
16
17
18
19
20
|
# File 'lib/volt/models/persistors/cookies.rb', line 10
def read_cookies
cookies = `document.cookie`
Hash[cookies.split(';').map do |v|
parts = v.split('=').map { |p| p = p.strip ; `decodeURIComponent(p)` }
parts << '' if parts.size == 1
parts
end]
end
|
#removed(attribute_name) ⇒ Object
78
79
80
81
82
|
# File 'lib/volt/models/persistors/cookies.rb', line 78
def removed(attribute_name)
writing_cookies do
write_cookie(attribute_name, '', expires: Time.now)
end
end
|
#write_cookie(key, value, options = {}) ⇒ Object
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
|
# File 'lib/volt/models/persistors/cookies.rb', line 22
def write_cookie(key, value, options={})
parts = []
parts << `encodeURIComponent(key)`
parts << '='
parts << `encodeURIComponent(value)`
parts << '; '
parts << 'max-age=' << options[:max_age] << '; ' if options[:max_age]
if options[:expires]
expires = options[:expires]
parts << 'expires=' << `expires.toGMTString()` << '; '
end
parts << 'path=' << options[:path] << '; ' if options[:path]
parts << 'domain=' << options[:domain] << '; ' if options[:domain]
parts << 'secure' if options[:secure]
cookie_val = parts.join
`document.cookie = cookie_val`
end
|
#writing_cookies ⇒ Object
84
85
86
87
88
|
# File 'lib/volt/models/persistors/cookies.rb', line 84
def writing_cookies
$writing_cookies = true
yield
$writing_cookies = false
end
|