Skip to content

Instantly share code, notes, and snippets.

@stevehodgkiss
Last active April 6, 2018 06:56
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save stevehodgkiss/4306359 to your computer and use it in GitHub Desktop.
Save stevehodgkiss/4306359 to your computer and use it in GitHub Desktop.
Allow specified session keys to be stored in a separate column using ActiveRecordStore. Useful for clearing sessions based on user_id.
class NativeColumnStore < ActiveRecord::SessionStore::Session
class << self
attr_reader :native_columns
def native_columns=(columns)
@native_columns = columns.map(&:to_s)
end
@native_columns = []
end
def data
@data ||= begin
unmarshaled_data = super
self.class.native_columns.each do |column|
unmarshaled_data.merge!(column => self[column]) if self[column].present?
end
unmarshaled_data
end
end
private
def marshal_data!
return false unless loaded?
self.class.native_columns.each do |column|
self[column] = data[column]
end
marshalled_data = self.class.marshal(data.except(*self.class.native_columns))
write_attribute(@@data_column_name, marshalled_data)
end
end
require 'spec_helper'
describe NativeColumnsStore do
subject(:store) { NativeColumnsStore.new(session_id: '123') }
before do
NativeColumnsStore.native_columns = [:user_id]
store.data[:test] = 'test_data'
store.data[:user_id] = 3
store.save!
store.reload
end
it 'merges user_id into #data' do
store.data[:user_id].should eq 3
end
it 'saves user_id in separate column' do
store.user_id.should eq 3
end
it 'doesnt store user_id in marshaled data column' do
marshaled_data = NativeColumnsStore.unmarshal(store.read_attribute(:data))
marshaled_data.count.should eq 1
marshaled_data.should have_key(:test)
end
after { NativeColumnsStore.native_columns = [] }
end
SSOServer::Application.config.session_store :active_record_store
ActiveRecord::SessionStore.session_class = UserSession
require 'native_columns_store'
class UserSession < NativeColumnsStore
self.native_columns = [:user_id]
end
@sigra
Copy link

sigra commented Apr 6, 2018

Cool. Thanks!

One more addition: store.data keeps keys as symbols. So, I changed native_columns setter to this:

def native_columns=(columns)
  @native_columns = columns.map(&:to_sym)
end

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment