Class: ActiveRecord::DelayTouching::State

Inherits:
Object
  • Object
show all
Defined in:
lib/activerecord/delay_touching/state.rb

Overview

Tracking of the touch state. This class has no class-level data, so you can store per-thread instances in thread-local variables.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeState

Returns a new instance of State.



11
12
13
14
15
# File 'lib/activerecord/delay_touching/state.rb', line 11

def initialize
  @records = Hash.new { Set.new }
  @already_updated_records = Hash.new { Set.new }
  @nesting = 0
end

Instance Attribute Details

#nestingObject

Returns the value of attribute nesting.



9
10
11
# File 'lib/activerecord/delay_touching/state.rb', line 9

def nesting
  @nesting
end

Instance Method Details

#add_record(record, *columns) ⇒ Object



40
41
42
43
44
45
# File 'lib/activerecord/delay_touching/state.rb', line 40

def add_record(record, *columns)
  columns << nil if columns.empty? #if no arguments are passed, we will use nil to infer default column
  columns.each do |column|
    @records[column] += [ record ] unless @already_updated_records[column].include?(record)
  end
end

#clear_recordsObject



47
48
49
50
# File 'lib/activerecord/delay_touching/state.rb', line 47

def clear_records
  @records.clear
  @already_updated_records.clear
end

#more_records?Boolean

Returns:

  • (Boolean)


36
37
38
# File 'lib/activerecord/delay_touching/state.rb', line 36

def more_records?
  @records.present?
end

#records_by_attrs_and_classObject

Return the records grouped by the attributes that were touched, and by class: [

[
  nil, { Person => [ person1, person2 ], Pet => [ pet1 ] }
],
[
  :neutered_at, { Pet => [ pet1 ] }
],

]



32
33
34
# File 'lib/activerecord/delay_touching/state.rb', line 32

def records_by_attrs_and_class
  @records.map { |attrs, records| [attrs, records.group_by(&:class)] }
end

#updated(attr, records) ⇒ Object



17
18
19
20
21
# File 'lib/activerecord/delay_touching/state.rb', line 17

def updated(attr, records)
  @records[attr].subtract records
  @records.delete attr if @records[attr].empty?
  @already_updated_records[attr] += records
end