Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Multiple session store implementation
RedisSessionStore.logger = Rails.logger
session_options = {:expire_after => 1.day, :key_prefix => 'sessions'}
MultiSessionStore.stores[:plain] = [RedisSessionStore, session_options.merge(:key => '_session_id')]
MultiSessionStore.stores[:secure] = [RedisSessionStore, session_options.merge(:key => '_secure_session_id', :secure => ['production', 'staging'].include?(Rails.env))]
MultiSessionStore.default_store = :plain
MultiSessionStore.routes = [
['/admin', :secure],
]
Shopify::Application.config.session_store :multi_session_store
require 'action_dispatch/middleware/session/abstract_store'
require 'active_support/core_ext/class/attribute_accessors'
class MultiSessionStore < ActionDispatch::Session::AbstractStore
cattr_accessor :stores, :routes, :default_store
self.stores = {}
def call(env)
instance(env).call(env)
end
def instance(env)
match = routes.find { |path, _| env['PATH_INFO'].start_with?(path) }
store_name = match ? match.last : default_store
var_name = "@#{store_name}"
instance_variable_fetch(var_name) do
klass, args = stores[store_name]
klass.new(@app, args)
end
end
def instance_variable_fetch(name, &blk)
instance_variable_get(name) || instance_variable_set(name, blk.call)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment