Class: Norman::Adapters::Cookie

Inherits:
Norman::Adapter show all
Defined in:
lib/norman/adapters/cookie.rb

Overview

Norman’s cookie adapter allows you to store a Norman database inside a zipped and signed string suitable for setting as a cookie. This can be useful for modelling things like basic shopping carts or form wizards. Keep in mind the data is signed, so it can’t be tampered with. However, the data is not encrypted, so somebody that wanted to could unzip and load the cookie data to see what’s inside. So don’t send this data client-side if it’s at all sensitive.

Constant Summary collapse

MAX_DATA_LENGTH =
4096

Instance Attribute Summary collapse

Attributes inherited from Norman::Adapter

#db, #name

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from Norman::Adapter

#db_for

Constructor Details

#initialize(options) ⇒ Cookie

Returns a new instance of Cookie.



26
27
28
29
30
# File 'lib/norman/adapters/cookie.rb', line 26

def initialize(options)
  @data     = options[:data]
  @verifier = ActiveSupport::MessageVerifier.new(options[:secret])
  super
end

Instance Attribute Details

#dataObject

Returns the value of attribute data.



18
19
20
# File 'lib/norman/adapters/cookie.rb', line 18

def data
  @data
end

#verifierObject (readonly)

Returns the value of attribute verifier.



17
18
19
# File 'lib/norman/adapters/cookie.rb', line 17

def verifier
  @verifier
end

Class Method Details

.max_data_lengthObject



22
23
24
# File 'lib/norman/adapters/cookie.rb', line 22

def self.max_data_length
  MAX_DATA_LENGTH
end

Instance Method Details

#export_dataObject



32
33
34
35
36
37
38
39
# File 'lib/norman/adapters/cookie.rb', line 32

def export_data
  cookie = verifier.generate(Zlib::Deflate.deflate(Marshal.dump(db)))
  length = cookie.bytesize
  if length > Cookie.max_data_length
    raise(NormanError, "Data is %s bytes, cannot exceed %s" % [length, Cookie.max_data_length])
  end
  cookie
end

#import_dataObject



41
42
43
# File 'lib/norman/adapters/cookie.rb', line 41

def import_data
  data.blank? ? {} : Marshal.load(Zlib::Inflate.inflate(verifier.verify(data)))
end

#load_databaseObject



45
46
47
48
# File 'lib/norman/adapters/cookie.rb', line 45

def load_database
  @db = import_data
  @db.map(&:freeze)
end

#save_databaseObject



50
51
52
# File 'lib/norman/adapters/cookie.rb', line 50

def save_database
  @data = export_data
end