Created
May 3, 2015 22:09
-
-
Save xeviknal/e39c93e39abc062e09c7 to your computer and use it in GitHub Desktop.
Redis Counter Cache - easy and non-locking
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
# 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 |
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
# app/models/event.rb | |
class Event < ActiveRecord::Base | |
include Counter::Definition | |
has_many :inscriptions | |
counter_for :inscriptions | |
end |
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
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