Recently I ran into a cookie overflow issue when using the Sidekiq gem for background processing. To solve the issue, I had to abandon using cookies for session storage, and instead use the database for sessions. It’s very easy to set up, and the instructions can be found in any Rails app in the config/initializers/session_store.rb file.

Something that isn’t outlined in the initializer, however, is that if you also create a Session model, but instead of descending from ActiveRecord::Base, descend from ActiveRecord::Session::Store, you can access your app’s sessions from anywhere in your application:

1 # File: app/models/session.rb
2 class Session < ActiveRecord::Session::Store; end

The Session object will behave like any other ActiveRecord model, with the exception of the #data method, which will return a Hash object.

Here’s an example of how you could use this to broadcast a message to all your site’s current visitors:

1 Session.all.each do |session|
2   session.data['flash'] ||= ActionDispatch::Flash::FlashHash.new
3   session.data['flash'][:alert] = 'Server going down in 10 minutes for scheduled maintenance.'
4   session.save!
5 end

You could even use it to display random site promotions. For example, using the clockwork gem, you could do this:

 1 # File: lib/promotions.rb
 2 require 'clockwork'
 3 require 'config/boot'
 4 require 'config/environment'
 5 
 6 every(1.minute, 'random.promos') do
 7   Session.all.each do |session|
 8     promo = Promo.all.sample
 9 
10     session['flash'] ||= ActionDispatch::Flash::FlashHash.new
11     session['flash'][:promo] = promo.call_to_action
12     session.save!
13   end
14 end
1 # File: app/views/application.html.erb
2 <% if flash[:promo].present? %>
3   <div id="promo"><%= raw flash[:promo] %></div>
4 <% end %>

Now the next time your site’s current visitors visit a new page they’ll be presented with the promotion, while any new visitors won’t see any promos until they’ve been browsing your site for at least 1 minute.

comments powered by Disqus