Module: Tron

Defined in:
lib/tron.rb,
lib/tron/failure.rb,
lib/tron/success.rb,
lib/tron/version.rb,
lib/tron/resultable.rb

Defined Under Namespace

Modules: Resultable, VERSION Classes: Failure, Success

Class Method Summary collapse

Class Method Details

.failure(code, attributes = {}) ⇒ Object

rubocop:disable Metrics/MethodLength



52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
# File 'lib/tron.rb', line 52

def self.failure(code, attributes = {}) # rubocop:disable Metrics/MethodLength
  code.respond_to?(:to_sym) ||
    raise(ArgumentError, 'Tron.failure must be called with a Symbol as first argument')

  attributes.respond_to?(:keys) ||
    raise(ArgumentError, 'The attributes Hash for Tron.failure must respond to #keys')

  attributes.respond_to?(:values) ||
    raise(ArgumentError, 'The attributes Hash for Tron.failure must respond to #values')

  Struct.new(:failure, *attributes.keys) do
    undef_method '[]='.to_sym
    members.each { |member| undef_method "#{member}=".to_sym }

    def success?
      false
    end

    def failure?
      true
    end

    def success
      nil
    end

    def code
      warn "DEPRECATION WARNING: Calling `#code` on a Tron object is deprecated and will be removed in Tron 2.0.0. Please use `#failure` instead. Called from `#{caller.first}`"

      failure
    end

    def on_success(_ = nil)
      self
    end

    def on_failure(proc = nil, &block)
      (proc || block).call self
    end
  end.new code.to_sym, *attributes.values.map(&:freeze)
end

.success(code, attributes = {}) ⇒ Object

rubocop:disable Metrics/MethodLength



10
11
12
13
14
15
16
17
18
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
# File 'lib/tron.rb', line 10

def self.success(code, attributes = {}) # rubocop:disable Metrics/MethodLength
  code.respond_to?(:to_sym) ||
    raise(ArgumentError, 'Tron.success must be called with a Symbol as first argument')

  attributes.respond_to?(:keys) ||
    raise(ArgumentError, 'The attributes Hash for Tron.success must respond to #keys')

  attributes.respond_to?(:values) ||
    raise(ArgumentError, 'The attributes Hash for Tron.success must respond to #values')

  Struct.new(:success, *attributes.keys) do
    undef_method '[]='.to_sym
    members.each { |member| undef_method "#{member}=".to_sym }

    def success?
      true
    end

    def failure?
      false
    end

    def failure
      nil
    end

    def code
      warn "DEPRECATION WARNING: Calling `#code` on a Tron object is deprecated and will be removed in Tron 2.0.0. Please use `#success` instead. Called from `#{caller.first}`"

      success
    end

    def on_success(proc = nil, &block)
      (proc || block).call self
    end

    def on_failure(_ = nil)
      self
    end
  end.new code.to_sym, *attributes.values.map(&:freeze)
end