class AttributesHistory::HistorySaver
Public Class Methods
new(changed_object, history_attributes, history_model)
click to toggle source
# File lib/attributes_history/history_saver.rb, line 3 def initialize(changed_object, history_attributes, history_model) @object = changed_object @history_attributes = history_attributes @history_model = history_model end
Public Instance Methods
save_if_needed()
click to toggle source
# File lib/attributes_history/history_saver.rb, line 9 def save_if_needed save_history_entry if ::AttributesHistory.enabled? && history_attributes_changed? end
Private Instance Methods
changes()
click to toggle source
# File lib/attributes_history/history_saver.rb, line 45 def changes if Gem::Version.new(Rails.version) >= Gem::Version.new('5.1.0') @object.saved_changes else @object.changes end end
history_attributes_changed?()
click to toggle source
# File lib/attributes_history/history_saver.rb, line 16 def history_attributes_changed? (changes.keys & @history_attributes).present? end
history_params()
click to toggle source
# File lib/attributes_history/history_saver.rb, line 32 def history_params Hash[@history_attributes.map { |f| [f, history_value_for(f)] }] end
history_value_for(attribute)
click to toggle source
# File lib/attributes_history/history_saver.rb, line 36 def history_value_for(attribute) # Use the previous value if it was changed, otherwise the current value if changes[attribute] changes[attribute].first else @object.public_send(attribute) end end
save_history_entry()
click to toggle source
# File lib/attributes_history/history_saver.rb, line 20 def save_history_entry history_association = @object.class.history_association(@history_attributes.first) history_entry = @object.public_send(history_association) .find_or_initialize_by(recorded_on: Date.current) # If there is an existing history record for today, just leave it as is, # otherwise, save the newly initialized one. history_entry.update!(history_params) if history_entry.new_record? end