Sha256: 82c782c804a8b6f9047e80a7675ff0f5c73fd91e888d7108d8b338e123bb29d6

Contents?: true

Size: 1.76 KB

Versions: 1

Compression:

Stored size: 1.76 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 

    # accessor for @session. Please use session and 
    # never @session directly.    
    def session
      @session  
    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.7 lib/merb/session/merb_drb_session.rb