Module: ConsoleThinkTwice

Defined in:
lib/console_think_twice.rb,
lib/console_think_twice/railtie.rb,
lib/console_think_twice/version.rb,
lib/console_think_twice/record_guard.rb,
lib/console_think_twice/configuration.rb,
lib/console_think_twice/relation_guard.rb

Overview

Confirmation prompts for destructive Active Record calls typed into a console.

>> User.first.destroy!
This will permanently destroy User #1 in production.
Cascades to: sessions, company_memberships, comments, api_keys
Confirm? (y/N)

Every guarded call takes force: true to skip the prompt. In a Rails app the railtie installs this on console boot only, so the web app, jobs and rails runner are untouched.

Defined Under Namespace

Modules: RecordGuard, RelationGuard Classes: Configuration, Railtie

Constant Summary collapse

Aborted =

Raised when a destructive call is declined, or when there is nobody to ask.

Class.new(StandardError)
CASCADING_STRATEGIES =
%i[destroy destroy_async delete_all].freeze
SUPPRESSION_KEY =
:console_think_twice_suppressed
VERSION =
"0.1.0"

Class Method Summary collapse

Class Method Details

.active?Boolean

Returns:

  • (Boolean)


55
56
57
# File 'lib/console_think_twice.rb', line 55

def active?
  !!@active
end

.configurationObject



28
29
30
# File 'lib/console_think_twice.rb', line 28

def configuration
  @configuration ||= Configuration.new
end

.configure {|configuration| ... } ⇒ Object

Yields:



32
33
34
# File 'lib/console_think_twice.rb', line 32

def configure
  yield configuration
end

.disable!Object



51
52
53
# File 'lib/console_think_twice.rb', line 51

def disable!
  @active = false
end

.guard(target, action:, force:) ⇒ Object

Confirms the call, then runs it with nested prompts suppressed so that a dependent: cascade, or a relation destroying its records one by one, only ever asks once.



61
62
63
64
65
66
67
68
69
# File 'lib/console_think_twice.rb', line 61

def guard(target, action:, force:)
  return yield if !active? || suppressed?

  count = affected_count(target)
  return yield if count.zero?

  confirm!(target, action, count) unless force
  suppressed { yield }
end

.install!Object



36
37
38
39
40
41
42
43
44
45
46
47
48
49
# File 'lib/console_think_twice.rb', line 36

def install!
  return false unless configuration.enabled?

  unless @installed
    ActiveRecord::Base.prepend(RecordGuard)
    ActiveRecord::Relation.prepend(RelationGuard)
    ActiveRecord::Associations::CollectionProxy.prepend(RelationGuard)
    @installed = true
  end

  @active = true
  announce
  true
end