Class: Sequel::ConnectionGuard::ModelGuard

Inherits:
Object
  • Object
show all
Defined in:
lib/sequel/extensions/connection_guard/model_guard.rb

Overview

An abstraction for safely accessing Sequel models.

See Also:

Since:

  • 0.1.0

Instance Method Summary collapse

Constructor Details

#initialize(ds, &class_body) ⇒ ModelGuard

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Returns a new instance of ModelGuard.

Parameters:

Since:

  • 0.1.0



17
18
19
20
21
22
23
# File 'lib/sequel/extensions/connection_guard/model_guard.rb', line 17

def initialize(ds, &class_body)
  @connection_guard = ds.connection_guard
  @table_name = ds.table_name
  @class_body = class_body
  @connected = false
  @model = nil
end

Instance Method Details

#force_execute(&block) ⇒ Object

Unsafely access the model. Will fail if connection fails.

Examples:

UserGuard.force_execute { |model| model.create(email: '[email protected]') }

Parameters:

  • block (Proc)

Raises:

  • (Sequel::DatabaseConnectionError)

    connection failure

Since:

  • 0.1.0



62
63
64
65
66
67
68
69
70
71
# File 'lib/sequel/extensions/connection_guard/model_guard.rb', line 62

def force_execute(&block)
  @connection_guard.force_execute do |connection|
    instantiate_model(connection) unless @connected

    yield @model
  end
rescue Sequel::DatabaseConnectionError => error
  @connected = false
  raise error
end

#raw_modelObject

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Since:

  • 0.1.0



75
76
77
78
# File 'lib/sequel/extensions/connection_guard/model_guard.rb', line 75

def raw_model
  try_instantiate_model if @model.nil?
  @model
end

#safe_execute(&block) ⇒ Object

Safely access the model.

Examples:

users = UserGuard.safe_execute do
  alive { |model| model.all }
  dead { [] }
end

Parameters:

  • block (Proc)

Since:

  • 0.1.0



37
38
39
40
41
42
43
44
45
46
47
48
49
50
# File 'lib/sequel/extensions/connection_guard/model_guard.rb', line 37

def safe_execute(&block)
  executor = Executor.new
  executor.instance_eval(&block)

  @connection_guard.force_execute do |connection|
    instantiate_model(connection) unless @connected

    executor.on_alive.call(@model)
  end
rescue Sequel::DatabaseConnectionError
  @connected = false

  executor.on_dead&.call
end