Class: Lyra::UserActionContext

Inherits:
Object
  • Object
show all
Defined in:
lib/lyra/correlation.rb

Overview

User action context for tracking what user action triggered events

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(action_type:, user_id: nil, controller: nil, action_name: nil, params: {}) ⇒ UserActionContext

Returns a new instance of UserActionContext.



95
96
97
98
99
100
101
102
103
# File 'lib/lyra/correlation.rb', line 95

def initialize(action_type:, user_id: nil, controller: nil, action_name: nil, params: {})
  @action_id = "action_#{Time.now.to_i}_#{SecureRandom.hex(6)}"
  @action_type = action_type  # :web_request, :api_call, :background_job, :console
  @user_id = user_id
  @controller = controller
  @action_name = action_name
  @params = sanitize_params(params)
  @started_at = Time.current
end

Instance Attribute Details

#action_id ⇒ Object (readonly)

Returns the value of attribute action_id.



93
94
95
# File 'lib/lyra/correlation.rb', line 93

def action_id
  @action_id
end

#action_name ⇒ Object (readonly)

Returns the value of attribute action_name.



93
94
95
# File 'lib/lyra/correlation.rb', line 93

def action_name
  @action_name
end

#action_type ⇒ Object (readonly)

Returns the value of attribute action_type.



93
94
95
# File 'lib/lyra/correlation.rb', line 93

def action_type
  @action_type
end

#controller ⇒ Object (readonly)

Returns the value of attribute controller.



93
94
95
# File 'lib/lyra/correlation.rb', line 93

def controller
  @controller
end

#params ⇒ Object (readonly)

Returns the value of attribute params.



93
94
95
# File 'lib/lyra/correlation.rb', line 93

def params
  @params
end

#user_id ⇒ Object (readonly)

Returns the value of attribute user_id.



93
94
95
# File 'lib/lyra/correlation.rb', line 93

def user_id
  @user_id
end

Class Method Details

.current ⇒ Object



118
119
120
# File 'lib/lyra/correlation.rb', line 118

def current
  Thread.current[:lyra_user_action_context]
end

.with_context(action_type:, user_id: nil, **options) ⇒ Object



122
123
124
125
126
127
128
129
130
131
132
133
# File 'lib/lyra/correlation.rb', line 122

def with_context(action_type:, user_id: nil, **options)
  context = new(action_type: action_type, user_id: user_id, **options)
  previous = Thread.current[:lyra_user_action_context]
  Thread.current[:lyra_user_action_context] = context

  # Also set correlation ID
  Lyra::Correlation.with_id(context.action_id) do
    yield context if block_given?
  end
ensure
  Thread.current[:lyra_user_action_context] = previous
end

Instance Method Details

#to_h ⇒ Object



105
106
107
108
109
110
111
112
113
114
115
# File 'lib/lyra/correlation.rb', line 105

def to_h
  {
    action_id: action_id,
    action_type: action_type,
    user_id: user_id,
    controller: controller,
    action_name: action_name,
    params: params,
    started_at: @started_at
  }
end