-
-
Save ashrafmajdee/354124e00b5fb1707a1a7747e48b2934 to your computer and use it in GitHub Desktop.
Multiple session store implementation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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