Skip to content

Instantly share code, notes, and snippets.

@t27duck
Last active August 29, 2015 14:07
Show Gist options
  • Save t27duck/844c82850d19d7978c77 to your computer and use it in GitHub Desktop.
Save t27duck/844c82850d19d7978c77 to your computer and use it in GitHub Desktop.
Initializer to be able to set an updated_by on paper trailed models. Giving it an ActiveRecord object will store whodunnit as "ModelName::Id". Calling updated_by will return the ActiveRecord object. This is also applied to the Version model.
module PaperTrail
module Model
# Creates and updated_by attributes on all paper trailed models. If given
# an ActiveRecord instance, PaperTrail.whodunnit will be set as
# "ModelName::Id". Calling updated_by will return the ActiveRecord object.
module InstanceMethods
def updated_by=(updater)
PaperTrail.whodunnit = PaperTrail::UpdatedByParser.to_s(updater)
end
def updated_by
PaperTrail::UpdatedByParser.from_s(PaperTrail.whodunnit)
end
end
end
# Added an updated_by attribute to all Version records. Returns an
# ActiveRecord object if whodunnit is formated as "ModelName::Id" and the
# record can be found. Else, it will return the string.
class Version < ::ActiveRecord::Base
def updated_by
PaperTrail::UpdatedByParser.from_s(whodunnit)
end
end
# Helper class that will take a formated whodunnit string and return an
# ActiveRecord object. It will also can take an ActiveRecord object and
# convert it to "ModelName::Id" format for storate in the verions table.
class UpdatedByParser
def self.to_s(updater)
return updater unless updater.is_a?(ActiveRecord::Base)
return nil if updater.new_record?
"#{updater.class.name}::#{updater.id}"
end
def self.from_s(updater)
return updater unless updater.respond_to?(:split)
parts = updater.split("::")
obj_id = parts.pop
parts.join.constantize.find(obj_id)
rescue ActiveRecord::RecordNotFound,NameError
updater
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment