Module: ConsoleAgent::BuiltinGuards

Defined in:
lib/console_agent/safety_guards.rb

Overview

Built-in guard: database write prevention Works on all Rails versions (5+) and all database adapters. Prepends a write-intercepting module once, controlled by a thread-local flag.

Defined Under Namespace

Modules: HttpBlocker, WriteBlocker

Class Method Summary collapse

Class Method Details

.database_writesObject



129
130
131
132
133
134
135
136
137
138
139
# File 'lib/console_agent/safety_guards.rb', line 129

def self.database_writes
  ->(& block) {
    ensure_write_blocker_installed!
    Thread.current[:console_agent_block_writes] = true
    begin
      block.call
    ensure
      Thread.current[:console_agent_block_writes] = false
    end
  }
end

.ensure_http_blocker_installed!Object



197
198
199
200
201
202
203
204
205
# File 'lib/console_agent/safety_guards.rb', line 197

def self.ensure_http_blocker_installed!
  return if @http_blocker_installed

  require 'net/http'
  unless Net::HTTP.ancestors.include?(HttpBlocker)
    Net::HTTP.prepend(HttpBlocker)
  end
  @http_blocker_installed = true
end

.ensure_write_blocker_installed!Object



141
142
143
144
145
146
147
148
149
# File 'lib/console_agent/safety_guards.rb', line 141

def self.ensure_write_blocker_installed!
  return if @write_blocker_installed

  connection = ActiveRecord::Base.connection
  unless connection.class.ancestors.include?(WriteBlocker)
    connection.class.prepend(WriteBlocker)
  end
  @write_blocker_installed = true
end

.http_mutationsObject



173
174
175
176
177
178
179
180
181
182
183
# File 'lib/console_agent/safety_guards.rb', line 173

def self.http_mutations
  ->(&block) {
    ensure_http_blocker_installed!
    Thread.current[:console_agent_block_http] = true
    begin
      block.call
    ensure
      Thread.current[:console_agent_block_http] = false
    end
  }
end

.mailersObject



185
186
187
188
189
190
191
192
193
194
195
# File 'lib/console_agent/safety_guards.rb', line 185

def self.mailers
  ->(&block) {
    old_value = ActionMailer::Base.perform_deliveries
    ActionMailer::Base.perform_deliveries = false
    begin
      block.call
    ensure
      ActionMailer::Base.perform_deliveries = old_value
    end
  }
end