Class: Camping::Models::Session

Inherits:
Base
  • Object
show all
Defined in:
lib/camping/session.rb

Overview

creation timestamp, and a column of serialized data called ivars.

Constant Summary collapse

RAND_CHARS =
[*'A'..'Z'] + [*'0'..'9'] + [*'a'..'z']

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.create_schemaObject

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


62
63
64
65
66
67
68
69
70
71
72
73
74
# File 'lib/camping/session.rb', line 62

def self.create_schema
    unless table_exists?
        ActiveRecord::Schema.define do
            create_table :sessions, :force => true do |t|
                t.column :id,          :integer, :null => false
                t.column :hashid,      :string,  :limit => 32
                t.column :created_at,  :datetime
                t.column :ivars,       :text
            end
        end
        reset_column_information
    end
end

.generate(cookies) ⇒ Object

Generates a new session ID and creates a row for the new session in the database.



30
31
32
33
34
35
36
# File 'lib/camping/session.rb', line 30

def self.generate cookies
    rand_max = RAND_CHARS.size
    sid = (0...32).inject("") { |ret,_| ret << RAND_CHARS[rand(rand_max)] }
    sess = Session.create :hashid => sid, :ivars => Camping::H[]
    cookies.camping_sid = sess.hashid
    sess
end

.persist(cookies) ⇒ Object

Gets the existing session based on the camping_sid available in cookies. If none is found, generates a new session.



40
41
42
43
44
45
46
47
48
# File 'lib/camping/session.rb', line 40

def self.persist cookies
    if cookies.camping_sid
        session = Camping::Models::Session.find_by_hashid cookies.camping_sid
    end
    unless session
        session = Camping::Models::Session.generate cookies
    end
    session
end

Instance Method Details

#[](k) ⇒ Object

:nodoc:



23
24
25
# File 'lib/camping/session.rb', line 23

def [](k) # :nodoc:
    self.ivars[k] rescue nil
end

#[]=(k, v) ⇒ Object

:nodoc:



20
21
22
# File 'lib/camping/session.rb', line 20

def []=(k, v) # :nodoc:
    self.ivars[k] = v
end