Module: ActiveRecord::Diff

Defined in:
lib/active_record/diff.rb

Defined Under Namespace

Modules: ClassMethod

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.included(base) ⇒ Object



9
10
11
12
# File 'lib/active_record/diff.rb', line 9

def self.included(base)
  base.class_attribute :diff_attrs
  base.extend ClassMethod
end

Instance Method Details

#diff(other_record = nil) ⇒ Object



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
# File 'lib/active_record/diff.rb', line 18

def diff(other_record = nil)
  if other_record.nil?
    old_record, new_record = self.class.find(id), self
  else
    old_record, new_record = self, other_record
  end

  if new_record.is_a?(Hash)
    diff_each(new_record) do |(attr_name, hash_value)|
      [attr_name, old_record.send(attr_name), hash_value]
    end
  else
    attrs = self.class.diff_attrs

    if attrs.nil?
      attrs = self.class.content_columns.map { |column| column.name.to_sym }
    elsif attrs.length == 1 && Hash === attrs.first
      columns = self.class.content_columns.map { |column| column.name.to_sym }

      attrs = columns + (attrs.first[:include] || []) - (attrs.first[:exclude] || [])
    end

    diff_each(attrs) do |attr_name|
      [attr_name, old_record.send(attr_name), new_record.send(attr_name)]
    end
  end
end

#diff?(record = nil) ⇒ Boolean

Returns:

  • (Boolean)


14
15
16
# File 'lib/active_record/diff.rb', line 14

def diff?(record = nil)
  not diff(record).empty?
end

#diff_each(enum) ⇒ Object



46
47
48
49
50
51
52
53
54
55
56
# File 'lib/active_record/diff.rb', line 46

def diff_each(enum)
  enum.inject({}) do |diff_hash, attr_name|
    attr_name, old_value, new_value = *yield(attr_name)

    unless old_value === new_value
      diff_hash[attr_name.to_sym] = [old_value, new_value]
    end

    diff_hash
  end
end