Skip to content

Setting whodunnit in the rails console

Mike Dillon edited this page Jun 22, 2016 · 22 revisions

In a console session you can manually set who is responsible like this:

PaperTrail.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!

if defined?(::Rails::Console)
  PaperTrail.whodunnit = "#{`whoami`.strip}: console"
elsif defined?(Rake) && Rake.application.name
  PaperTrail.whodunnit = "#{`whoami`.strip}: #{File.basename($0)} #{ARGV.join ' '}"
end

You can also force every console user to type something with this monkey patch

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.whodunnit = "#{name.chomp} - from console"
      initialize.bind(self).call(*args)
    end
  end
end