module ActiveRecordSnapshot::Snapped

Public Instance Methods

save_snapshot() click to toggle source
# File lib/active_record_snapshot/snapped.rb, line 64
def save_snapshot
  # this should be refactored somewhere...
  record = self 
  snapshot_mashie = Hashie::Mash.new 
  

  record.class.snapped_attributes.each_pair do |att_name, att_config|
    att_str = att_name.to_s
    # if there is a change, this copies the prior version. If not, this stores the current attribute value
    
    is_att_changed = !(record.changes[att_str].nil? )
    previous_or_current_val = is_att_changed ? record.changes[att_str][-1] : record.attributes[att_str]

    if att_config[:when] == :always
      # when :always, we save either the previous value (if changed) or the current value
      snapshot_mashie[att_name] = previous_or_current_val
    elsif att_config[:when] == :dirty && is_att_changed
      snapshot_mashie[att_name] = previous_or_current_val
    end
  end

  # now create snapshot_record with snapshot_mashie as the assigned attributes
  # TODO: code smell, according to Demeter
  new_snapshot = self.class.snapshot_class_name.constantize.create(snapshot_mashie)

  return new_snapshot
end