opal/browser/cookies.rb in opal-browser-0.2.0 vs opal/browser/cookies.rb in opal-browser-0.3.0

- old
+ new

@@ -3,14 +3,21 @@ module Browser # Allows manipulation of browser cookies. # # @see https://developer.mozilla.org/en-US/docs/Web/API/document.cookie +# +# Usage: +# +# cookies = Browser::Cookies.new(`document`) +# cookies["my-cookie"] = "monster" +# cookies.delete("my-cookie") +# class Cookies # Default cookie options. DEFAULT = { - expires: Time.now + 1.day, + expires: Time.now + 60 * 60 * 24, secure: false } include Enumerable @@ -28,16 +35,16 @@ # # @param name [String] the name of the cookie # # @return [Object] def [](name) - matches = `#@document.cookie`.scan(/#{Regexp.escape(name.encode_uri_component)}=([^;]*)/) + matches = `#@document.cookie`.scan(/#{Regexp.escape(FormData.encode(name))}=([^;]*)/) return if matches.empty? - result = matches.map {|cookie| - JSON.parse(cookie.match(/^.*?=(.*)$/)[1].decode_uri_component) + result = matches.flatten.map {|value| + JSON.parse(FormData.decode(value)) } result.length == 1 ? result.first : result end @@ -51,11 +58,13 @@ # @option options [Time] :expires the expire date # @option options [String] :path the path the cookie is valid on # @option options [String] :domain the domain the cookie is valid on # @option options [Boolean] :secure whether the cookie is secure or not def []=(name, value, options = {}) - `#@document.cookie = #{encode name, value.is_a?(String) ? value : JSON.dump(value), @options.merge(options)}` + string = value.is_a?(String) ? value : JSON.dump(value) + encoded_value = encode(name, string, @options.merge(options)) + `#@document.cookie = #{encoded_value}` end # Delete a cookie. # # @param name [String] the name of the cookie @@ -108,13 +117,13 @@ protected def encode(key, value, options = {}) io = StringIO.new - io << key.encode_uri_component << ?= << value.encode_uri_component << '; ' + io << FormData.encode(key) << ?= << FormData.encode(value) << '; ' io << 'max-age=' << options[:max_age] << '; ' if options[:max_age] - io << 'expires=' << options[:expires].to_utc << '; ' if options[:expires] + io << 'expires=' << options[:expires].utc << '; ' if options[:expires] io << 'path=' << options[:path] << '; ' if options[:path] io << 'domain=' << options[:domain] << '; ' if options[:domain] io << 'secure' if options[:secure] io.string