Module: Iry::TransformConstraints

Extended by:
TransformConstraints
Included in:
TransformConstraints
Defined in:
lib/iry/transform_constraints.rb

Overview

Implementation of Iry methods, helps ensuring the main module focus on documentation

Instance Method Summary collapse

Instance Method Details

#destroy(model) ⇒ Handlers::Model

Parameters:

Returns:



129
130
131
132
133
134
135
136
137
# File 'lib/iry/transform_constraints.rb', line 129

def destroy(model)
  constraint_result = handle_constraints(model) { model.destroy }

  if constraint_result.nil?
    return false
  end

  return constraint_result
end

#handle_constraints(model) { ... } ⇒ nil, Handlers::Model

Parameters:

Yields:

Returns:



10
11
12
13
14
# File 'lib/iry/transform_constraints.rb', line 10

def handle_constraints(model, &block)
  handle_constraints!(model, &block)
rescue StatementInvalid
  return nil
end

#handle_constraints!(model) { ... } ⇒ Handlers::Model

Parameters:

Yields:

Returns:



19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
# File 'lib/iry/transform_constraints.rb', line 19

def handle_constraints!(model, &block)
  # Allows checking if Iry has been activated (handling).
  # Number is used to support nested handle_constraints!
  Thread.current[:iry] ||= 0
  Thread.current[:iry] += 1

  nested_constraints!(model, &block)
rescue StatementInvalid => err
  # Imports errors from "nested" models back into the parent, to ensure
  # `errors` is populated and the record is considered invalid

  # Skip if error has been added to the same object being handled
  if err.record.object_id == model.object_id
    raise
  end

  # Adds the error only if it hasn't been added already
  already_imported = model
    .errors
    .each
    .lazy
    .select { |ae| ae.respond_to?(:inner_error) }
    .map { |ae| ae.inner_error }
    .include?(err.error)
  if !already_imported
    model.errors.import(err.error)
  end

  raise
ensure
  # "Pop" handle_constraints! usage, when 0, no constraint handling should
  # happen
  Thread.current[:iry] -= 1
end

#save(model) ⇒ Boolean

Parameters:

Returns:

  • (Boolean)


102
103
104
105
106
107
108
109
110
111
# File 'lib/iry/transform_constraints.rb', line 102

def save(model, ...)
  success = nil
  constraint_model = handle_constraints(model) { success = model.save(...) }

  if constraint_model
    return success
  end

  return false
end

#save!(model) ⇒ true

Parameters:

Returns:

  • (true)

Raises:



117
118
119
120
121
122
123
124
125
# File 'lib/iry/transform_constraints.rb', line 117

def save!(model, ...)
  constraint_model = handle_constraints(model) { model.save!(...) }

  if constraint_model
    return true
  end

  raise ConstraintViolation.new(model)
end