module CounterCacheWithConditions::ActiveRecord

Public Instance Methods

counter_cache_with_conditions(association_name, counter_name, conditions, block = nil) click to toggle source

@param association_name extended belongs_to association name (like :user) @param counter_name name of counter cache column @param conditions hash with equal conditions, like {:read => false, :source => 'message'}, no nesting @param conditions array with checked attributes names, in this case block is required.

usage looks like [:read, :source], lambda{|read, source| read == false && source == 'message'}

@param block proc object that take list of arguments specified in conditions parameter, should compare them and return boolean

# File lib/counter_cache_with_conditions/active_record.rb, line 10
def counter_cache_with_conditions(association_name, counter_name, conditions, block = nil)
  unless ancestors.include? InstanceMethods
    include InstanceMethods
    after_create :counter_cache_with_conditions_after_create
    before_update :counter_cache_with_conditions_before_update
    before_destroy :counter_cache_with_conditions_before_destroy

    cattr_accessor :counter_cache_with_conditions_options
    self.counter_cache_with_conditions_options = []
  end

  # TODO make readonly
  ref = reflect_on_association(association_name)
  ref.klass.send(:attr_readonly, counter_name.to_sym) if ref.klass.respond_to?(:attr_readonly)
  conditions = [conditions, block] if conditions.is_a? Array
  self.counter_cache_with_conditions_options << [ref.klass, ref.foreign_key, counter_name, conditions]
end