Sha256: 9f55d4ba374de67078f6a3b238ac6f69b07b57fa618ba6b8595281c362c619a3

Contents?: true

Size: 1.64 KB

Versions: 1

Compression:

Stored size: 1.64 KB

Contents

module Merb
  
  module SessionMixin

    def setup_session
      MERB_LOGGER.info("Setting up session")
      @session = Merb::Session.persist(cookies)
      @fingerprint_before = Marshal.dump(@session).hash
    end

    def finalize_session
      MERB_LOGGER.info("Finalize session")
      unless Marshal.dump(@session).hash == @fingerprint_before
        @session.save
      end
      @headers['Set-Cookie'] = @cookies.map { |k,v| "#{k}=#{escape(v)}; path=/" if v != @k[k] } - [nil]
    end 

  end
  
  class Session
  
    attr_reader :sess_id
  
    def []=(k, v) # :nodoc:
        (@data||={})[k] = v rescue nil
    end
    def [](k) # :nodoc:
        @data[k] rescue nil
    end
  
    def initialize(sess_id,data={})
      @data = data || {}
      @sess_id = sess_id
    end  
    
    def save
      Merb::DRbSession[@sess_id] = @data
    end  
  
    RAND_CHARS = [*'A'..'Z'] + [*'0'..'9'] + [*'a'..'z']
  
    # Generates a new session ID and creates a row for the new session in the database.
    def self.generate(cookies)
      rand_max = RAND_CHARS.size
      sid = (0...32).inject("") { |ret,_| ret << RAND_CHARS[rand(rand_max)] }
      sess = Merb::DRbSession.create(:sess_id => sid, :data => {})
      cookies[:sess_id] = sid
      new(sid, sess)
    end
  
    # Gets the existing session based on the <tt>camping_sid</tt> available in cookies.
    # If none is found, generates a new session.
    def self.persist cookies
      if cookies[:sess_id]
        session = new(cookies[:sess_id], Merb::DRbSession[cookies[:sess_id]])
      end
      unless session
        session = Merb::Session.generate(cookies)
      end
      session
    end
  end
  
end  

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
merb-0.0.8 lib/merb/session/merb_drb_session.rb