module DatastaxRails::AttributeMethods::Dirty

Change tracking for attributes. Builds on ActiveModel::Dirty in order to reset changes on save.

Public Instance Methods

reload(*) click to toggle source

reload the record and clears changed attributes.

Calls superclass method
# File lib/datastax_rails/attribute_methods/dirty.rb, line 39
def reload(*)
  super.tap do
    @previously_changed.clear
    @changed_attributes.clear
  end
end
write_attribute(attr, value) click to toggle source
Calls superclass method
# File lib/datastax_rails/attribute_methods/dirty.rb, line 46
def write_attribute(attr, value)
  attr = attr.to_s
  loaded_attributes[attr] = true

  # The attribute already has an unsaved change.
  if attribute_changed?(attr)
    old = @changed_attributes[attr]
    @changed_attributes.delete(attr) unless _field_changed?(attr, old, value)
  else
    old = clone_attribute_value(:read_attribute, attr)
    @changed_attributes[attr] = old if _field_changed?(attr, old, value)
  end

  super
end

Private Instance Methods

_field_changed?(attr, old, value) click to toggle source
# File lib/datastax_rails/attribute_methods/dirty.rb, line 64
def _field_changed?(attr, old, value)
  if (column = column_for_attribute(attr))
    if column.number? && (changes_from_nil_to_empty_string?(column, old, value) ||
                          changes_from_zero_to_string?(old, value))
      value = nil
    else
      value = column.type_cast(value, self)
    end
  end

  old != value
end
changes_from_nil_to_empty_string?(_column, old, value) click to toggle source
# File lib/datastax_rails/attribute_methods/dirty.rb, line 77
def changes_from_nil_to_empty_string?(_column, old, value)
  # We don't record it as a change if the value changes from nil to ''.
  # If an old value of 0 is set to '' we want this to get changed to nil as otherwise it'll
  # be typecast back to 0 (''.to_i => 0)
  (old.nil? || old == 0) && value.blank?
end
changes_from_zero_to_string?(old, value) click to toggle source
# File lib/datastax_rails/attribute_methods/dirty.rb, line 84
def changes_from_zero_to_string?(old, value)
  # For columns with old 0 and value non-empty string
  old == 0 && value.is_a?(String) && value.present? && non_zero?(value)
end
non_zero?(value) click to toggle source
# File lib/datastax_rails/attribute_methods/dirty.rb, line 89
def non_zero?(value)
  value !~ /\A0+(\.0+)?\z/
end