Class: CounterOne::Counter

Inherits:
Object
  • Object
show all
Defined in:
lib/counter_one/counter.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(model, relation, options) ⇒ Counter

Returns a new instance of Counter.



6
7
8
9
10
# File 'lib/counter_one/counter.rb', line 6

def initialize(model, relation, options)
  @model = model
  @relation = [relation].flatten
  @options = options
end

Instance Attribute Details

#modelObject (readonly)

Returns the value of attribute model.



4
5
6
# File 'lib/counter_one/counter.rb', line 4

def model
  @model
end

#optionsObject (readonly)

Returns the value of attribute options.



4
5
6
# File 'lib/counter_one/counter.rb', line 4

def options
  @options
end

#relationObject (readonly)

Returns the value of attribute relation.



4
5
6
# File 'lib/counter_one/counter.rb', line 4

def relation
  @relation
end

Instance Method Details

#recalculate_scopeObject



50
51
52
# File 'lib/counter_one/counter.rb', line 50

def recalculate_scope
  options[:recalculate_scope]
end

#relation_chainObject



54
55
56
57
58
59
60
61
# File 'lib/counter_one/counter.rb', line 54

def relation_chain
  klass = model

  relation.each_with_object([]) { |rel, chain|
    chain << klass.reflect_on_association(rel).chain.map(&:name).reverse
    klass = rel.to_s.classify.constantize
  }.flatten
end

#update_counter(record, operator, changed_record = nil) ⇒ Object



12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
# File 'lib/counter_one/counter.rb', line 12

def update_counter(record, operator, changed_record = nil)
  counter_record = record
  klass = model

  relation.each do |rel|
    unless klass.reflect_on_association(rel)
      raise "Can't find relation #{rel} for #{klass.to_s}"
    end

    counter_record = counter_record.send(rel)
    klass = counter_record.class

    return unless counter_record
  end

  if options[:only]
    unless options[:only].is_a?(Proc)
      raise ArgumentError.new(":only must be a Proc with conditions")
    end

    return unless options[:only].call(record)
  end

  if changed_record
    return if options[:only] ? condition_not_changed?(record, changed_record) : relation_id_not_changed?(record)
  end

  if counter_record
    column = options[:column] || "#{record.class.to_s.tableize}_count"

    if counter_record.is_a?(ActiveRecord::Associations::CollectionProxy)
      counter_record.each { |r| r.send(operator, column) }
    else
      counter_record.send(operator, column)
    end
  end
end