Last active
March 1, 2019 18:44
-
-
Save andhart/d4c7ac07c8e04612007455826662182d to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module Recordingable | |
extend ActiveSupport::Concern | |
included do | |
has_many :recordings, as: :recordingable | |
after_commit :record_item | |
end | |
module ClassMethods | |
attr_reader :fields | |
private | |
def record(opts = []) | |
@fields = opts | |
end | |
end | |
def current_version?(recording) | |
true if recording == self.recordings.order("created_at asc").last | |
end | |
# Creates old "fake" record for display | |
# purposes only. Do record.throwback_to(recording) | |
def throwback_to(recording) | |
obj = self | |
details = JSON.parse(recording.details) | |
details.each do |k,v| | |
if obj.has_attribute?(k) | |
obj[k.to_sym] = v | |
elsif obj.respond_to?("#{k}=") | |
obj.send("#{k}=", v) | |
else | |
puts "no attribute found" | |
end | |
end | |
obj | |
end | |
private | |
def record_item | |
return false unless item_changed? | |
Recording.create({ | |
details: serialize_attributes, | |
user: Current.user, | |
account: Current.user.account, | |
ip_address: Current.ip, | |
action: action, | |
recordingable: self | |
}) | |
end | |
def action | |
transaction_include_any_action?([:create]) ? "created" : "updated" | |
end | |
def item_changed? | |
last_details = self.recordings.order("created_at asc").last.try(:details) | |
last_details == serialize_attributes ? false : true | |
end | |
def serialize_attributes | |
output = {} | |
self.class.fields.each do |k,v| | |
output[k] = self.try(k) | |
end | |
output.to_json | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment