-
Notifications
You must be signed in to change notification settings - Fork 0
/
benefits_of_call_method.rb
49 lines (39 loc) · 1.28 KB
/
benefits_of_call_method.rb
1
2
3
4
5
6
7
8
9
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
# Source: https://dev.to/devteam/benefits-of-having-a-call-method-for-your-ruby-object-30dk
# Takeaways
# 1. Defining a `call` method at a module or class level can enable easy test mocking
# Defining a `call` method at a module or class level can enable easy test mocking
puts '# Defining a `call` method at a module or class level can enable easy test mocking'
module Handler
def self.call(package:); end
end
module Notifier
def self.call(package:); end
end
class Package
attr_reader :origin, :destination, :handler, :notifier
def initialize(origin:, destination:, notifier: Notifier, handler: Handler)
@origin = origin
@destination = destination
@handler = handler
@notifier = notifier
end
def deliver!(with_notification: true)
notifier.call(package: self) if with_notification
handler.call(package: self)
end
end
require 'test-unit'
class Tester < Test::Unit::TestCase
def test_assert_not_sending_notification
# By having the notifier `raise`, we'll know if it was called.
notifier = ->(package:) { raise }
handler = ->(package:) { :handled }
package = Package.new(
origin: :here,
destination: :there,
notifier: notifier,
handler: handler
)
assert(package.deliver!(with_notification: false) == :handled)
end
end