Skip to content

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).

Manually setting

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

Setting automatically based on current OS user

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
}

Require users to enter their name when launching rails console

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