Class: ExceptionTransformer::Transformer

Inherits:
Object
  • Object
show all
Defined in:
lib/exception_transformer/transformer.rb

Constant Summary collapse

MAX_MESSAGE_SIZE =
100

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(strategy) ⇒ Transformer

Returns a new instance of Transformer.



8
9
10
11
# File 'lib/exception_transformer/transformer.rb', line 8

def initialize(strategy)
  self.strategy = strategy
  self.mappings = {}
end

Instance Attribute Details

#delegateObject

Returns the value of attribute delegate.



4
5
6
# File 'lib/exception_transformer/transformer.rb', line 4

def delegate
  @delegate
end

#mappingsObject

Returns the value of attribute mappings.



4
5
6
# File 'lib/exception_transformer/transformer.rb', line 4

def mappings
  @mappings
end

#strategyObject

Returns the value of attribute strategy.



4
5
6
# File 'lib/exception_transformer/transformer.rb', line 4

def strategy
  @strategy
end

#validatorObject

Returns the value of attribute validator.



4
5
6
# File 'lib/exception_transformer/transformer.rb', line 4

def validator
  @validator
end

Instance Method Details

#after_rescue(obj, e, calling_method, except: [], use_default: true, opts: {}) ⇒ Object



26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
# File 'lib/exception_transformer/transformer.rb', line 26

def after_rescue(obj, e, calling_method, except: [], use_default: true, opts: {})
  with_reporting do
    case strategy
    when :delegate
      obj.instance_exec(e, calling_method, opts, &delegate)
    when :rewrite, :regex
      exception, message = find_target(e, except, use_default)
    end

    if exception.present?
      raise exception, message.first(MAX_MESSAGE_SIZE), e.backtrace
    else
      # Couldn't transform the exception to a defined mapping.
      raise e
    end
  end
end

#after_yield(obj, result, calling_method, except: [], use_default: true, opts: {}) ⇒ Object



44
45
46
47
48
49
50
51
# File 'lib/exception_transformer/transformer.rb', line 44

def after_yield(obj, result, calling_method, except: [], use_default: true, opts: {})
  with_reporting do
    case strategy
    when :validate
      obj.instance_exec(result, calling_method, opts, &validator)
    end
  end
end

#register_target(target, exceptions) ⇒ Object



13
14
15
16
17
18
19
20
21
22
23
24
# File 'lib/exception_transformer/transformer.rb', line 13

def register_target(target, exceptions)
  case strategy
  when :validate
    self.validator = target
  when :delegate
    self.delegate  = target
  when :rewrite, :regex
    exceptions.each do |klass|
      self.mappings[klass] = target
    end
  end
end