Class: Whodunit::Current

Inherits:
ActiveSupport::CurrentAttributes
  • Object
show all
Defined in:
lib/whodunit/current.rb

Overview

Thread-safe current user context using Rails CurrentAttributes.

This class provides a thread-safe way to store the current user for auditing purposes. It leverages Rails’ CurrentAttributes functionality to ensure proper isolation across threads and requests.

Examples:

Setting a user

Whodunit::Current.user = User.find(123)
Whodunit::Current.user = 123  # Can also set by ID directly

Getting the user ID

Whodunit::Current.user_id  # => 123

In a controller

class ApplicationController < ActionController::Base
  before_action :set_current_user

  private

  def set_current_user
    Whodunit::Current.user = current_user
  end
end

Since:

  • 0.1.0

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Attribute Details

#userInteger?

Returns the current user ID.

Returns:

  • (Integer, nil)

    the current user ID



32
# File 'lib/whodunit/current.rb', line 32

attribute :user

Class Method Details

.original_user_assignmentObject

Store the original user= method before we override it

Since:

  • 0.1.0



36
# File 'lib/whodunit/current.rb', line 36

alias original_user_assignment user=

.resetObject

Override reset to ensure our custom setter is preserved

Since:

  • 0.1.0



55
56
57
58
59
# File 'lib/whodunit/current.rb', line 55

def reset
  super
  # Redefine our custom setter after reset
  _redefine_user_setter
end

.user=(user) ⇒ Integer?

Set the current user by object or ID.

Accepts either a user object (responds to #id) or a user ID directly. The user ID is stored for database operations.

Examples:

Whodunit::Current.user = User.find(123)
Whodunit::Current.user = 123
Whodunit::Current.user = nil  # Clear current user

Parameters:

  • user (Object, Integer, nil)

    user object or user ID

Returns:

  • (Integer, nil)

    the stored user ID

Since:

  • 0.1.0



49
50
51
52
# File 'lib/whodunit/current.rb', line 49

def user=(user)
  value = user.respond_to?(:id) ? user.id : user
  original_user_assignment(value)
end

.user_idInteger?

Get the current user ID for database storage.

Examples:

Whodunit::Current.user = User.find(123)
Whodunit::Current.user_id  # => 123

Returns:

  • (Integer, nil)

    the current user ID

Since:

  • 0.1.0



74
75
76
# File 'lib/whodunit/current.rb', line 74

def self.user_id
  user
end