Class | Camping::Models::Session |
In: |
lib/camping/session.rb
|
Parent: | Base |
A database table for storing Camping sessions. Contains a unique 32-character hashid, a creation timestamp, and a column of serialized data called ivars.
RAND_CHARS | = | [*'A'..'Z'] + [*'0'..'9'] + [*'a'..'z'] |
Builds the session table in the database. To be used in your application‘s create method.
Like so:
def Blog.create Camping::Models::Session.create_schema unless Blog::Models::Post.table_exists? ActiveRecord::Schema.define(&Blog::Models.schema) end end
# File lib/camping/session.rb, line 62 62: def self.create_schema 63: unless table_exists? 64: ActiveRecord::Schema.define do 65: create_table :sessions, :force => true do |t| 66: t.column :id, :integer, :null => false 67: t.column :hashid, :string, :limit => 32 68: t.column :created_at, :datetime 69: t.column :ivars, :text 70: end 71: end 72: reset_column_information 73: end 74: end
Generates a new session ID and creates a row for the new session in the database.
# File lib/camping/session.rb, line 30 30: def self.generate cookies 31: rand_max = RAND_CHARS.size 32: sid = (0...32).inject("") { |ret,_| ret << RAND_CHARS[rand(rand_max)] } 33: sess = Session.create :hashid => sid, :ivars => Camping::H[] 34: cookies.camping_sid = sess.hashid 35: sess 36: end
Gets the existing session based on the camping_sid available in cookies. If none is found, generates a new session.
# File lib/camping/session.rb, line 40 40: def self.persist cookies 41: if cookies.camping_sid 42: session = Camping::Models::Session.find_by_hashid cookies.camping_sid 43: end 44: unless session 45: session = Camping::Models::Session.generate cookies 46: end 47: session 48: end