Skip to content

Instantly share code, notes, and snippets.

@tarynsauer
Last active January 2, 2016 00:59
Show Gist options
  • Save tarynsauer/8227306 to your computer and use it in GitHub Desktop.
Save tarynsauer/8227306 to your computer and use it in GitHub Desktop.
class MockSession
def initialize(cookies)
@cookies = cookies
@data = cookies['rack.session'] ## Gets session hash as base64 encoded marshalled data set
if @data
@data = @data.unpack("m*").first ### Decodes data as string
@data = Marshal.load(@data) ### Converts serialized data into a Ruby hash
else
@data = {}
end
end
## Defines method for getting a mock session key's value.
def [](key)
@data[key]
end
## Defines method for adding a new key/value pair to session || changing value of existing key.
def []=(key, value)
@data[key] = value
session_data = Marshal.dump(@data) ### Serializes data
session_data = [session_data].pack("m*") ### Encodes string as base64 marshalled data set
@cookies.merge("rack.session=#{Rack::Utils.escape(session_data)}") ## URI excaping, merges session hash data
raise "session variable not set" unless @cookies['rack.session'] == session_data
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment