Skip to content

Instantly share code, notes, and snippets.

@xeviknal
Created May 3, 2015 22:09
Show Gist options
  • Save xeviknal/e39c93e39abc062e09c7 to your computer and use it in GitHub Desktop.
Save xeviknal/e39c93e39abc062e09c7 to your computer and use it in GitHub Desktop.
Redis Counter Cache - easy and non-locking
# app/models/concerns/counter.rb
require 'active_support/concern'
module Counter
module Updater
extend ActiveSupport::Concern
included do
after_create :update_counters
end
def update_counters
self.class.redis_counters.each do |relation_name|
counter_name = "#{self.class.name.pluralize.underscore}_counter"
self.send(relation_name).send(counter_name).increment
end
end
module ClassMethods
def redis_counters
@counters ||= []
end
def update_counter_for(relation_name)
redis_counters << relation_name
end
end
end
module Definition
extend ActiveSupport::Concern
included do
include Redis::Objects
end
module ClassMethods
def counter_for(relation_name)
counter "#{relation_name}_counter"
define_method "#{relation_name}_count" do
self.send("#{relation_name}_counter").value
end
end
end
end
end
# app/models/event.rb
class Event < ActiveRecord::Base
include Counter::Definition
has_many :inscriptions
counter_for :inscriptions
end
class Inscriptions < ActiveRecord::Base
include Counter::Updater
belongs_to :event
update_counter_for :event
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment