Module: RailsOnboarding::Onboardable

Extended by:
ActiveSupport::Concern
Defined in:
app/models/concerns/rails_onboarding/onboardable.rb

Constant Summary collapse

MAX_TOOLTIPS_SHOWN =

Maximum sizes for JSON fields to prevent memory issues

1000
MAX_MILESTONES_ACHIEVED =
500
MAX_JSON_SIZE_BYTES =

~64KB for TEXT columns

65_535

Instance Method Summary collapse

Instance Method Details

#achieve_milestone!(milestone_key, session_id: nil) ⇒ Object



347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
# File 'app/models/concerns/rails_onboarding/onboardable.rb', line 347

def achieve_milestone!(milestone_key, session_id: nil)
  return false unless RailsOnboarding.configuration.enable_milestones
  return false if milestone_achieved?(milestone_key)

  milestone_config = RailsOnboarding.configuration.milestone_by_key(milestone_key)
  return false unless milestone_config

  points_earned = milestone_config[:points] || 0
  achieved_at = Time.current

  self.milestones_achieved ||= []
  # Store as hash with timestamp for new achievements
  self.milestones_achieved << {
    "key" => milestone_key.to_s,
    "achieved_at" => achieved_at.iso8601
  }
  self.milestone_points = (milestone_points || 0) + points_earned
  self.last_milestone_at = achieved_at

  persist_and_track! do
    AnalyticsEvent.track_milestone_achieved(
      user: self,
      milestone_key: milestone_key,
      points_earned: points_earned,
      session_id: session_id
    )
  end

  milestone_config
end

#achieved_milestonesObject

Milestones



295
296
297
298
299
300
301
302
303
304
305
306
307
308
# File 'app/models/concerns/rails_onboarding/onboardable.rb', line 295

def achieved_milestones
  milestones = milestones_achieved || []

  # Warn about old format if any string entries are found
  if milestones.any? { |m| m.is_a?(String) }
    RailsOnboarding::Deprecation.deprecate_format(
      "Storing milestones as array of strings",
      new_format: "array of hashes with 'key' and 'achieved_at' fields",
      version: "2.0.0"
    )
  end

  milestones.map { |m| m.is_a?(Hash) ? m["key"] : m.to_s }
end

#available_tooltipsObject

Get available tooltips that haven't been shown



601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
# File 'app/models/concerns/rails_onboarding/onboardable.rb', line 601

def available_tooltips
  return [] unless RailsOnboarding.configuration.enable_tooltips

  RailsOnboarding.configuration.feature_tooltips.select do |key, _config|
    show_feature_tooltip?(key)
  end.map do |key, config|
    {
      id: key.to_s,
      title: config[:title],
      content: config[:content],
      target: config[:target],
      position: config[:position] || "top"
    }
  end
end

#can_go_back?Boolean

Rollback & Navigation Methods

Returns:

  • (Boolean)


431
432
433
434
435
# File 'app/models/concerns/rails_onboarding/onboardable.rb', line 431

def can_go_back?
  return false unless onboarding_current_step
  current_index = RailsOnboarding.configuration.step_index(onboarding_current_step)
  current_index && current_index > 0
end

#complete_onboarding!(session_id: nil, completion_time: nil) ⇒ Object



183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
# File 'app/models/concerns/rails_onboarding/onboardable.rb', line 183

def complete_onboarding!(session_id: nil, completion_time: nil)
  persist_and_track!(
    {
      onboarding_completed: true,
      onboarding_completed_at: Time.current,
      onboarding_current_step: nil
    }.merge(replay_reset_attributes)
  ) do
    AnalyticsEvent.track_onboarding_completed(
      user: self,
      completion_time: completion_time,
      was_skipped: false,
      session_id: session_id
    )
    check_and_achieve_completion_milestones(session_id: session_id)
  end
end

#complete_onboarding_step!(step_name, session_id: nil, time_spent: nil) ⇒ void Also known as: complete_step

This method returns an undefined value.

Complete the current onboarding step and advance to the next

This method handles the core onboarding flow logic:

  1. Validates the step exists in the configuration
  2. Tracks step completion for analytics
  3. Checks and awards any relevant milestones
  4. Advances to the next step or completes onboarding if on the last step

Parameters:

  • step_name (String, Symbol)

    the name of the step to complete

  • session_id (String) (defaults to: nil)

    optional session identifier for tracking

  • time_spent (Integer) (defaults to: nil)

    optional time spent on step in seconds

Raises:

  • (ActiveRecord::RecordInvalid)

    if the update fails



152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
# File 'app/models/concerns/rails_onboarding/onboardable.rb', line 152

def complete_onboarding_step!(step_name, session_id: nil, time_spent: nil)
  current_index = RailsOnboarding.configuration.step_index(step_name)

  if current_index.nil?
    # If step not found, complete onboarding
    complete_onboarding!(session_id: session_id)
    return
  end

  next_step = RailsOnboarding.configuration.steps[current_index + 1]

  if next_step
    update!(onboarding_current_step: next_step[:name])
  else
    complete_onboarding!(session_id: session_id)
  end

  # Track step completion and check for milestones only after the step
  # change above has actually persisted - otherwise a failed save would
  # still leave behind an analytics event (and possibly an awarded
  # milestone) for a step completion that never happened.
  AnalyticsEvent.track_step_completed(
    user: self,
    step_name: step_name,
    step_index: current_index,
    time_spent: time_spent,
    session_id: session_id
  )
  check_and_achieve_step_milestones(step_name, session_id: session_id)
end

#current_onboarding_stepObject Also known as: current_step_info



117
118
119
120
121
122
123
124
# File 'app/models/concerns/rails_onboarding/onboardable.rb', line 117

def current_onboarding_step
  return nil if onboarding_completed?

  step_name = onboarding_current_step || RailsOnboarding.configuration.steps.first[:name]
  step = RailsOnboarding.configuration.step_by_name(step_name)

  step || RailsOnboarding.configuration.steps.first
end

#dismiss_tooltip(tooltip_id, session_id: nil) ⇒ Object

Dismiss a tooltip (marks as shown and tracks as dismissed)



631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
# File 'app/models/concerns/rails_onboarding/onboardable.rb', line 631

def dismiss_tooltip(tooltip_id, session_id: nil)
  # Mark as shown without tracking (to avoid duplicate event)
  self.feature_tooltips_shown ||= {}
  self.feature_tooltips_shown[tooltip_id.to_s] = Time.current.iso8601
  save!

  # Track as dismissed, not shown
  AnalyticsEvent.track_tooltip_interaction(
    user: self,
    tooltip_feature: tooltip_id,
    action: "dismissed",
    session_id: session_id
  )
  true
rescue StandardError => e
  Rails.logger.error("Failed to dismiss tooltip: #{e.message}")
  false
end

#end_onboarding_replay!Object



531
532
533
534
535
536
# File 'app/models/concerns/rails_onboarding/onboardable.rb', line 531

def end_onboarding_replay!
  return false unless self.class.onboarding_replay_supported?

  update!(replay_reset_attributes)
  true
end

#go_back!(session_id: nil) ⇒ Object



443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
# File 'app/models/concerns/rails_onboarding/onboardable.rb', line 443

def go_back!(session_id: nil)
  return false unless can_go_back?

  prev_step = previous_onboarding_step
  return false unless prev_step

  from_step = onboarding_current_step

  persist_and_track!(onboarding_current_step: prev_step[:name]) do
    AnalyticsEvent.track_custom_event(
      user: self,
      event_name: "onboarding_step_back",
      event_data: { from_step: from_step, to_step: prev_step[:name] },
      session_id: session_id
    )
  end
  true
end

#go_to_step!(step_name, session_id: nil) ⇒ Object



462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
# File 'app/models/concerns/rails_onboarding/onboardable.rb', line 462

def go_to_step!(step_name, session_id: nil)
  step = RailsOnboarding.configuration.step_by_name(step_name)
  return false unless step

  from_step = onboarding_current_step

  persist_and_track!(onboarding_current_step: step_name) do
    AnalyticsEvent.track_custom_event(
      user: self,
      event_name: "onboarding_step_jump",
      event_data: { from_step: from_step, to_step: step_name },
      session_id: session_id
    )
  end
  true
end

#mark_onboarding_step_replayed!(step_name) ⇒ Object

Record that the user has now seen this step. No-op outside a replay.



549
550
551
552
553
554
555
556
# File 'app/models/concerns/rails_onboarding/onboardable.rb', line 549

def mark_onboarding_step_replayed!(step_name)
  return false unless replaying_onboarding?
  return false if onboarding_step_replayed?(step_name)

  self.onboarding_replay_steps = (onboarding_replay_steps || []) + [ step_name.to_s ]
  save!
  true
end

#mark_tooltip_shown!(feature, session_id: nil) ⇒ Object Also known as: mark_tooltip_shown



259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
# File 'app/models/concerns/rails_onboarding/onboardable.rb', line 259

def mark_tooltip_shown!(feature, session_id: nil)
  self.feature_tooltips_shown ||= {}

  # Trim old entries if approaching limit
  if feature_tooltips_shown.size >= MAX_TOOLTIPS_SHOWN
    trim_oldest_tooltips
  end

  self.feature_tooltips_shown[feature.to_s] = Time.current.iso8601

  persist_and_track! do
    AnalyticsEvent.track_tooltip_interaction(
      user: self,
      tooltip_feature: feature,
      action: "shown",
      session_id: session_id
    )
  end
end

#milestone_achieved?(milestone_key) ⇒ Boolean

Returns:

  • (Boolean)


310
311
312
# File 'app/models/concerns/rails_onboarding/onboardable.rb', line 310

def milestone_achieved?(milestone_key)
  achieved_milestones.include?(milestone_key.to_s)
end

#milestone_achieved_at(milestone_key) ⇒ Time?

Get the timestamp when a specific milestone was achieved

This method supports both old (string array) and new (hash array) formats for backwards compatibility. For old format data, it returns last_milestone_at as a fallback since per-milestone timestamps weren't stored.

Examples:

user.milestone_achieved_at(:first_login) #=> 2025-01-15 10:30:00 UTC

Parameters:

  • milestone_key (String, Symbol)

    the milestone key to lookup

Returns:

  • (Time, nil)

    the achievement timestamp, or nil if not achieved



324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
# File 'app/models/concerns/rails_onboarding/onboardable.rb', line 324

def milestone_achieved_at(milestone_key)
  return nil unless milestone_achieved?(milestone_key)

  # Support both old array format and new hash format
  milestones = milestones_achieved || []
  milestone = milestones.find do |m|
    if m.is_a?(Hash)
      m["key"].to_s == milestone_key.to_s
    else
      m.to_s == milestone_key.to_s
    end
  end

  # Return timestamp if available, otherwise return last_milestone_at as fallback
  if milestone.is_a?(Hash) && milestone["achieved_at"]
    Time.parse(milestone["achieved_at"])
  else
    last_milestone_at
  end
rescue StandardError
  last_milestone_at
end

#milestones_availableObject



382
383
384
385
# File 'app/models/concerns/rails_onboarding/onboardable.rb', line 382

def milestones_available
  return [] unless RailsOnboarding.configuration.enable_milestones
  RailsOnboarding.configuration.milestones.reject { |m| milestone_achieved?(m[:key]) }
end

#needs_onboarding?Boolean

Determines if the user needs to go through onboarding

This method checks the configuration setting and user state to determine if onboarding should be shown. It supports different strategies:

  • :new_users - Only users created within the last hour
  • :all_users - All users who haven't completed onboarding
  • Proc - Custom logic defined in configuration

Returns:

  • (Boolean)

    true if onboarding is needed, false otherwise



74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
# File 'app/models/concerns/rails_onboarding/onboardable.rb', line 74

def needs_onboarding?
  return false if onboarding_completed?
  return false if onboarding_skipped?

  case RailsOnboarding.configuration.onboarding_required_for
  when :new_users
    # Users imported before the gem was installed can have a NULL
    # created_at. An unknown signup time is not a recent one, so they're
    # treated as existing users rather than crashing on every request.
    created_at.present? && created_at > 1.hour.ago
  when :all_users
    true
  when Proc
    RailsOnboarding.configuration.onboarding_required_for.call(self)
  else
    true
  end
end

#next_onboarding_stepObject Also known as: next_step



129
130
131
132
133
134
135
136
137
# File 'app/models/concerns/rails_onboarding/onboardable.rb', line 129

def next_onboarding_step
  return nil if onboarding_completed?

  current_index = RailsOnboarding.configuration.step_index(onboarding_current_step)
  return RailsOnboarding.configuration.steps.first unless current_index

  next_step = RailsOnboarding.configuration.steps[current_index + 1]
  next_step
end

#onboarding_progressInteger Also known as: onboarding_progress_percentage

Calculate onboarding progress as a percentage

Returns a value between 0 and 100 representing how far the user has progressed through the onboarding flow. Calculation is based on current step position divided by total steps.

Examples:

user.onboarding_progress #=> 75

Returns:

  • (Integer)

    progress percentage (0-100)



102
103
104
105
106
107
108
109
110
111
112
# File 'app/models/concerns/rails_onboarding/onboardable.rb', line 102

def onboarding_progress
  return 100 if onboarding_completed?
  return 0 unless onboarding_current_step

  current_index = RailsOnboarding.configuration.step_index(onboarding_current_step)
  return 0 if current_index.nil?

  total_steps = RailsOnboarding.configuration.total_steps

  ((current_index + 1).to_f / total_steps * 100).round
end

#onboarding_skipped?Boolean

Onboarding skipped check

Returns:

  • (Boolean)


651
652
653
# File 'app/models/concerns/rails_onboarding/onboardable.rb', line 651

def onboarding_skipped?
  onboarding_skipped == true
end

#onboarding_step_replayed?(step_name) ⇒ Boolean

Has the user been shown this step since the current replay began?

True whenever no replay is active, so callers can gate auto-advance on it unconditionally and get the ordinary behaviour outside a replay.

Returns:

  • (Boolean)


542
543
544
545
546
# File 'app/models/concerns/rails_onboarding/onboardable.rb', line 542

def onboarding_step_replayed?(step_name)
  return true unless replaying_onboarding?

  (onboarding_replay_steps || []).map(&:to_s).include?(step_name.to_s)
end

#onboarding_stepsArray<Hash>

Returns the onboarding steps for this user

If multi-tenant support is enabled and the user has an organization, returns organization-specific steps. Otherwise returns the default steps.

Returns:

  • (Array<Hash>)

    Array of step configurations



572
573
574
575
576
577
578
579
580
581
# File 'app/models/concerns/rails_onboarding/onboardable.rb', line 572

def onboarding_steps
  # Check for organization-specific steps via MultiTenant
  if respond_to?(:current_organization_id) && current_organization_id
    MultiTenant.steps_for(current_organization_id)
  elsif respond_to?(:organization_id) && organization_id
    MultiTenant.steps_for(organization_id)
  else
    RailsOnboarding.configuration.steps
  end
end

#previous_onboarding_stepObject Also known as: previous_step



437
438
439
440
441
# File 'app/models/concerns/rails_onboarding/onboardable.rb', line 437

def previous_onboarding_step
  return nil unless can_go_back?
  current_index = RailsOnboarding.configuration.step_index(onboarding_current_step)
  RailsOnboarding.configuration.steps[current_index - 1]
end

#recent_milestones(limit: 5) ⇒ Object



387
388
389
390
391
392
393
# File 'app/models/concerns/rails_onboarding/onboardable.rb', line 387

def recent_milestones(limit: 5)
  return [] unless RailsOnboarding.configuration.enable_milestones

  achieved_milestones.last(limit).map do |key|
    RailsOnboarding.configuration.milestone_by_key(key)
  end.compact
end

#replaying_onboarding?Boolean

Is this user currently re-walking the flow?

False once they finish, so a completed user is never stuck in replay.

Returns:

  • (Boolean)


516
517
518
519
520
521
# File 'app/models/concerns/rails_onboarding/onboardable.rb', line 516

def replaying_onboarding?
  return false unless self.class.onboarding_replay_supported?
  return false if onboarding_completed?

  onboarding_replay_started_at.present?
end

#reset_onboarding!(clear_milestones: true) ⇒ Boolean Also known as: reset_onboarding

Clear onboarding state so the user starts over.

Milestones are cleared by default. achieve_milestone! is idempotent (it returns false for anything already in milestones_achieved), so leaving them behind means a user sent back through the flow can never re-earn them and finishes with no milestone notice at all. Pass clear_milestones: false to keep them - worth doing where a host app's milestones record real achievements rather than onboarding progress.

Any in-flight replay is cancelled: a bare reset drops the user back to the default behaviour, where a step whose :complete_if already passes is advanced past automatically. Use restart_onboarding! to reset and replay.

Parameters:

  • clear_milestones (Boolean) (defaults to: true)

    also wipe milestones, points and last_milestone_at (default: true)

Returns:

  • (Boolean)

    true



236
237
238
239
240
241
242
243
244
245
246
247
248
# File 'app/models/concerns/rails_onboarding/onboardable.rb', line 236

def reset_onboarding!(clear_milestones: true)
  attributes = {
    onboarding_completed: false,
    onboarding_completed_at: nil,
    onboarding_skipped: false,
    onboarding_current_step: nil,
    feature_tooltips_shown: {}
  }
  attributes.merge!(milestone_reset_attributes) if clear_milestones
  attributes.merge!(replay_reset_attributes)

  update!(attributes)
end

#reset_tooltips!Object

Reset all tooltips (mark all as not shown)



280
281
282
283
# File 'app/models/concerns/rails_onboarding/onboardable.rb', line 280

def reset_tooltips!
  self.feature_tooltips_shown = {}
  save!
end

#restart_onboarding!(session_id: nil, clear_milestones: true) ⇒ Object

Reset and immediately re-enter the flow at step one.

Unlike a bare reset this turns replay mode on, so a user whose host-app data already satisfies every :complete_if walks the steps again instead of being auto-advanced straight back to "completed" on their next visit to /onboarding. See replaying_onboarding?.



485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
# File 'app/models/concerns/rails_onboarding/onboardable.rb', line 485

def restart_onboarding!(session_id: nil, clear_milestones: true)
  previous_step = onboarding_current_step
  was_completed = onboarding_completed

  reset_onboarding!(clear_milestones: clear_milestones)
  start_onboarding_replay!
  start_onboarding!(session_id: session_id)

  AnalyticsEvent.track_custom_event(
    user: self,
    event_name: "onboarding_restarted",
    event_data: { previous_step: previous_step, was_completed: was_completed },
    session_id: session_id
  )
end

#show_feature_tooltip?(feature) ⇒ Boolean

Feature tooltips

Returns:

  • (Boolean)


251
252
253
254
255
256
257
# File 'app/models/concerns/rails_onboarding/onboardable.rb', line 251

def show_feature_tooltip?(feature)
  return false unless RailsOnboarding.configuration.enable_tooltips
  return false unless RailsOnboarding.configuration.feature_tooltips[feature.to_s]

  shown_tooltips = (feature_tooltips_shown || {})
  !shown_tooltips[feature.to_s]
end

#skip_onboarding!(session_id: nil) ⇒ Object



201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
# File 'app/models/concerns/rails_onboarding/onboardable.rb', line 201

def skip_onboarding!(session_id: nil)
  persist_and_track!(
    {
      onboarding_completed: true,
      onboarding_completed_at: Time.current,
      onboarding_skipped: true,
      onboarding_current_step: nil
    }.merge(replay_reset_attributes)
  ) do
    AnalyticsEvent.track_onboarding_completed(
      user: self,
      completion_time: nil,
      was_skipped: true,
      session_id: session_id
    )
  end
end

#skip_onboarding_step!(step_name, session_id: nil) ⇒ Object Also known as: skip_step



409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
# File 'app/models/concerns/rails_onboarding/onboardable.rb', line 409

def skip_onboarding_step!(step_name, session_id: nil)
  current_index = RailsOnboarding.configuration.step_index(step_name)
  return unless current_index

  next_step = RailsOnboarding.configuration.steps[current_index + 1]

  if next_step
    update!(onboarding_current_step: next_step[:name])
  else
    complete_onboarding!(session_id: session_id)
  end

  AnalyticsEvent.track_step_skipped(
    user: self,
    step_name: step_name,
    step_index: current_index,
    session_id: session_id
  )
end

#start_onboarding!(session_id: nil) ⇒ Object



395
396
397
398
399
400
401
402
403
404
405
406
407
# File 'app/models/concerns/rails_onboarding/onboardable.rb', line 395

def start_onboarding!(session_id: nil)
  return if onboarding_completed?

  # Set initial step if not already set
  if onboarding_current_step.nil? && RailsOnboarding.configuration.steps.any?
    update!(onboarding_current_step: RailsOnboarding.configuration.steps.first[:name])
  end

  AnalyticsEvent.track_onboarding_started(
    user: self,
    session_id: session_id
  )
end

#start_onboarding_replay!Boolean

Returns false when the host app hasn't run the replay migration.

Returns:

  • (Boolean)

    false when the host app hasn't run the replay migration



524
525
526
527
528
529
# File 'app/models/concerns/rails_onboarding/onboardable.rb', line 524

def start_onboarding_replay!
  return false unless self.class.onboarding_replay_supported?

  update!(onboarding_replay_started_at: Time.current, onboarding_replay_steps: [])
  true
end

#step_completed?(step_name) ⇒ Boolean

Check if a specific step has been completed

Returns:

  • (Boolean)


584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
# File 'app/models/concerns/rails_onboarding/onboardable.rb', line 584

def step_completed?(step_name)
  return false unless step_name

  step_index = RailsOnboarding.configuration.step_index(step_name)
  return false if step_index.nil?

  # If onboarding is completed, all steps are completed
  return true if onboarding_completed?

  # Check if current step is past the requested step
  current_index = RailsOnboarding.configuration.step_index(onboarding_current_step)
  return false if current_index.nil?

  current_index > step_index
end

#tooltip_shown?(tooltip_id) ⇒ Boolean

Check if a specific tooltip has been shown to this user

This method directly checks the user's feature_tooltips_shown hash to determine if a tooltip was marked as shown, regardless of whether the tooltip is configured in the application settings.

Parameters:

  • tooltip_id (String, Symbol)

    the tooltip identifier

Returns:

  • (Boolean)

    true if the tooltip has been shown, false otherwise



625
626
627
628
# File 'app/models/concerns/rails_onboarding/onboardable.rb', line 625

def tooltip_shown?(tooltip_id)
  shown_tooltips = feature_tooltips_shown || {}
  shown_tooltips.key?(tooltip_id.to_s)
end

#total_milestone_pointsObject



378
379
380
# File 'app/models/concerns/rails_onboarding/onboardable.rb', line 378

def total_milestone_points
  milestone_points || 0
end

#track_tooltip_interaction!(feature, action, session_id: nil) ⇒ Object



285
286
287
288
289
290
291
292
# File 'app/models/concerns/rails_onboarding/onboardable.rb', line 285

def track_tooltip_interaction!(feature, action, session_id: nil)
  AnalyticsEvent.track_tooltip_interaction(
    user: self,
    tooltip_feature: feature,
    action: action,
    session_id: session_id
  )
end