-
Notifications
You must be signed in to change notification settings - Fork 884
Setting whodunnit in the rails console
Tyler Rick edited this page Aug 15, 2018
·
22 revisions
This page describes ways of setting whodunnit
for use in the rails console or other rails commands / rake tasks (like rake db:migrate
).
In a console session you can manually set who is responsible like this:
PaperTrail.request.whodunnit = 'Andy Stewart'
widget.update_attributes :name => 'Wibble'
widget.versions.last.whodunnit # Andy Stewart
You can avoid having to do this manually by setting your initializer to pick up the username of the current user from the OS, like this:
# config/initializers/paper_trail.rb
# the following line is required for PaperTrail >= 4.0.0 with Rails
PaperTrail::Rails::Engine.eager_load!
# Defer evaluation in case we're using spring loader (otherwise it would be something like "spring app | app | started 13 secs ago | development")
PaperTrail.request.whodunnit = ->() {
if Rails.const_defined?('Console') || $rails_rake_task
"#{`whoami`.strip}: console"
else
"#{`whoami`.strip}: #{File.basename($PROGRAM_NAME)} #{ARGV.join ' '}"
end
}
You can also force every console user to type enter their name:
module Rails
class Console
initialize = instance_method(:initialize)
define_method :initialize do |*args|
puts 'Welcome'
name = nil
until name.present? do
puts 'Who are you?'
name = gets
puts 'Mmmm?' unless name.present?
end
puts "Hi #{name}"
PaperTrail.request.whodunnit = "#{name.chomp} - from console"
initialize.bind(self).call(*args)
end
end
end