Class: AmplitudeExperiment::AmplitudeCookie
- Inherits:
-
Object
- Object
- AmplitudeExperiment::AmplitudeCookie
- Defined in:
- lib/experiment/cookie.rb
Overview
This class provides utility functions for parsing and handling identity from Amplitude cookies.
Class Method Summary collapse
-
.cookie_name(api_key, new_format: false) ⇒ String
Get the cookie name that Amplitude sets for the provided.
-
.generate(device_id, new_format: false) ⇒ String
Generates a cookie string to set for the Amplitude Javascript SDK.
-
.parse(amplitude_cookie, new_format: false) ⇒ User
Parse a cookie string and returns user.
Class Method Details
.cookie_name(api_key, new_format: false) ⇒ String
Get the cookie name that Amplitude sets for the provided
12 13 14 15 16 17 18 19 20 21 22 23 |
# File 'lib/experiment/cookie.rb', line 12 def self.(api_key, new_format: false) raise ArgumentError, 'Invalid Amplitude API Key' if api_key.nil? if new_format raise ArgumentError, 'Invalid Amplitude API Key' if api_key.length < 10 return "AMP_#{api_key[0..9]}" end raise ArgumentError, 'Invalid Amplitude API Key' if api_key.length < 6 "amp_#{api_key[0..5]}" end |
.generate(device_id, new_format: false) ⇒ String
Generates a cookie string to set for the Amplitude Javascript SDK
59 60 61 62 63 64 65 66 67 68 |
# File 'lib/experiment/cookie.rb', line 59 def self.generate(device_id, new_format: false) return "#{device_id}.........." unless new_format user_session_hash = { 'deviceId' => device_id } json_data = JSON.generate(user_session_hash) encoded_json = URI.encode_www_form_component(json_data) Base64.strict_encode64(encoded_json) end |
.parse(amplitude_cookie, new_format: false) ⇒ User
Parse a cookie string and returns user
30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 |
# File 'lib/experiment/cookie.rb', line 30 def self.parse(, new_format: false) if new_format begin decoding = Base64.decode64().force_encoding('UTF-8') json_data = URI.decode_www_form_component(decoding) user_session_hash = JSON.parse(json_data) return User.new(user_id: user_session_hash['userId'], device_id: user_session_hash['deviceId']) rescue StandardError => e puts "Error parsing the Amplitude cookie: #{e.}" return nil end end values = .split('.', -1) user_id = nil unless values[1].nil? || values[1].empty? begin user_id = Base64.decode64(values[1]).force_encoding('UTF-8') rescue StandardError user_id = nil end end User.new(user_id: user_id, device_id: values[0]) end |