Class: CounterOne::Counter
- Inherits:
-
Object
- Object
- CounterOne::Counter
- Defined in:
- lib/counter_one/counter.rb
Instance Attribute Summary collapse
-
#model ⇒ Object
readonly
Returns the value of attribute model.
-
#options ⇒ Object
readonly
Returns the value of attribute options.
-
#relation ⇒ Object
readonly
Returns the value of attribute relation.
Instance Method Summary collapse
-
#initialize(model, relation, options) ⇒ Counter
constructor
A new instance of Counter.
- #recalculate_scope ⇒ Object
- #relation_chain ⇒ Object
- #update_counter(record, operator, changed_record = nil) ⇒ Object
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, ) @model = model @relation = [relation].flatten @options = end |
Instance Attribute Details
#model ⇒ Object (readonly)
Returns the value of attribute model.
4 5 6 |
# File 'lib/counter_one/counter.rb', line 4 def model @model end |
#options ⇒ Object (readonly)
Returns the value of attribute options.
4 5 6 |
# File 'lib/counter_one/counter.rb', line 4 def @options end |
#relation ⇒ Object (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_scope ⇒ Object
50 51 52 |
# File 'lib/counter_one/counter.rb', line 50 def recalculate_scope [:recalculate_scope] end |
#relation_chain ⇒ Object
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 [:only] unless [:only].is_a?(Proc) raise ArgumentError.new(":only must be a Proc with conditions") end return unless [:only].call(record) end if changed_record return if [:only] ? condition_not_changed?(record, changed_record) : relation_id_not_changed?(record) end if counter_record column = [: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 |