Module: RailsConsoleAi::BuiltinGuards

Defined in:
lib/rails_console_ai/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



226
227
228
229
230
231
232
233
234
235
236
# File 'lib/rails_console_ai/safety_guards.rb', line 226

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

.ensure_http_blocker_installed!Object



298
299
300
301
302
303
304
305
306
# File 'lib/rails_console_ai/safety_guards.rb', line 298

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



238
239
240
241
242
243
244
245
246
# File 'lib/rails_console_ai/safety_guards.rb', line 238

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



272
273
274
275
276
277
278
279
280
281
282
# File 'lib/rails_console_ai/safety_guards.rb', line 272

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

.mailersObject



284
285
286
287
288
289
290
291
292
293
294
295
296
# File 'lib/rails_console_ai/safety_guards.rb', line 284

def self.mailers
  ->(&block) {
    return block.call if Thread.current[:rails_console_ai_bypass_guards]

    old_value = ActionMailer::Base.perform_deliveries
    ActionMailer::Base.perform_deliveries = false
    begin
      block.call
    ensure
      ActionMailer::Base.perform_deliveries = old_value
    end
  }
end