Class: Browser::Cookies
- Includes:
- Enumerable
- Defined in:
- opal/browser/cookies.rb
Overview
Allows manipulation of browser cookies.
Constant Summary collapse
- DEFAULT =
Default cookie options.
{ expires: Time.now + 1.day, secure: false }
Instance Attribute Summary collapse
-
#keys ⇒ Array<String>
readonly
All the cookie names.
-
#options ⇒ Object
readonly
Returns the value of attribute options.
-
#values ⇒ Array
readonly
All the cookie values.
Instance Method Summary collapse
-
#[](name) ⇒ Object
Access the cookie with the given name.
-
#[]=(name, value, options = {}) ⇒ Object
Set a cookie.
-
#clear ⇒ self
Delete all the cookies.
-
#delete(name) ⇒ Object
Delete a cookie.
-
#each {|key, value| ... } ⇒ self
Enumerate the cookies.
-
#initialize(document) ⇒ Cookies
constructor
Create a new Cookies wrapper.
Constructor Details
#initialize(document) ⇒ Cookies
Create a new Browser::Cookies wrapper.
22 23 24 25 |
# File 'opal/browser/cookies.rb', line 22 def initialize(document) @document = document @options = DEFAULT.dup end |
Instance Attribute Details
#keys ⇒ Array<String> (readonly)
Returns all the cookie names.
68 69 70 71 72 |
# File 'opal/browser/cookies.rb', line 68 def keys Array(`#@document.cookie.split(/; /)`).map {|| .split(/\s*=\s*/).first } end |
#options ⇒ Object (readonly)
Returns the value of attribute options.
17 18 19 |
# File 'opal/browser/cookies.rb', line 17 def @options end |
#values ⇒ Array (readonly)
Returns all the cookie values.
76 77 78 79 80 |
# File 'opal/browser/cookies.rb', line 76 def values keys.map {|key| self[key] } end |
Instance Method Details
#[](name) ⇒ Object
Access the cookie with the given name.
32 33 34 35 36 37 38 39 40 41 42 |
# File 'opal/browser/cookies.rb', line 32 def [](name) matches = `#@document.cookie`.scan(/#{Regexp.escape(name.encode_uri_component)}=([^;]*)/) return if matches.empty? result = matches.map {|| JSON.parse(.match(/^.*?=(.*)$/)[1].decode_uri_component) } result.length == 1 ? result.first : result end |
#[]=(name, value, options = {}) ⇒ Object
Set a cookie.
55 56 57 |
# File 'opal/browser/cookies.rb', line 55 def []=(name, value, = {}) `#@document.cookie = #{encode name, value.is_a?(String) ? value : JSON.dump(value), @options.merge()}` end |
#clear ⇒ self
Delete all the cookies
101 102 103 104 105 106 107 |
# File 'opal/browser/cookies.rb', line 101 def clear keys.each {|key| delete key } self end |
#delete(name) ⇒ Object
Delete a cookie.
62 63 64 |
# File 'opal/browser/cookies.rb', line 62 def delete(name) `#@document.cookie = #{encode name, '', expires: Time.now}` end |
#each {|key, value| ... } ⇒ self
Enumerate the cookies.
88 89 90 91 92 93 94 95 96 |
# File 'opal/browser/cookies.rb', line 88 def each(&block) return enum_for :each unless block keys.each {|key| yield key, self[key] } self end |