Module: DbSession

Defined in:
lib/db_session.rb,
lib/db_session/version.rb,
lib/generators/db_session/install_generator.rb

Defined Under Namespace

Modules: Generators

Constant Summary collapse

SESSION_KEY =
:db_session_store_id
VERSION =
'1.0.0'

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.setup {|_self| ... } ⇒ Object

Yields:

  • (_self)

Yield Parameters:

  • _self (DbSession)

    the object that the method was called on



11
12
13
# File 'lib/db_session.rb', line 11

def self.setup
  yield self
end

Instance Method Details

#add_to_db_session(key, value) ⇒ Object



42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
# File 'lib/db_session.rb', line 42

def add_to_db_session(key, value)
  main_data_object = {}

  db_session_id = session[SESSION_KEY]
  db_session = DbSessionStore.find_by(id: db_session_id) if db_session_id

  main_data_object = JSON.parse(db_session.serialized_data) if db_session
  main_data_object[key] = value

  if db_session
    db_session.serialized_data = main_data_object.to_json
    db_session.save
  else
    db_session = DbSessionStore.create(serialized_data: main_data_object.to_json)
  end

  session[SESSION_KEY] = db_session.id

  clear_expired_sessions
end

#clear_db_sessionObject



63
64
65
66
67
68
69
# File 'lib/db_session.rb', line 63

def clear_db_session
  db_session_id = session[SESSION_KEY]
  if db_session_id
    db_session = DbSessionStore.find_by(id: db_session_id)
    db_session.destroy if db_session
  end
end

#clear_expired_sessionsObject



71
72
73
74
75
76
77
78
# File 'lib/db_session.rb', line 71

def clear_expired_sessions
  begin
    ClearSessionStoresWorker.perform_async(session_validity)
  rescue Exception => e
    logger.error e.message.colorize(:color => :red, :background => :black)
    logger.error 'CONSEQUENCE: Old sessions are not been cleared from the database'.colorize(:color => :yellow, :background => :black)
  end
end

#get_from_db_session(key = nil) ⇒ Object



15
16
17
18
19
20
21
22
23
24
25
26
27
28
# File 'lib/db_session.rb', line 15

def get_from_db_session(key=nil)
  db_session_id = session[SESSION_KEY]
  db_session = DbSessionStore.find_by(id: db_session_id) if db_session_id

  if db_session
    main_data_object = JSON.parse(db_session.serialized_data)

    if key
      return main_data_object[key]
    else
      return main_data_object
    end
  end
end

#set_db_session(key, value) ⇒ Object



30
31
32
33
34
35
36
37
38
39
40
# File 'lib/db_session.rb', line 30

def set_db_session(key, value)
  clear_db_session

  main_data_object = {}
  main_data_object[key] = value

  db_session = DbSessionStore.create(serialized_data: main_data_object.to_json)
  session[SESSION_KEY] = db_session.id

  clear_expired_sessions
end