-
Notifications
You must be signed in to change notification settings - Fork 1
/
fluent_interfaces.html
73 lines (61 loc) · 1.72 KB
/
fluent_interfaces.html
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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
<html>
<head>
<title>Ruby DSL Patterns - fluent interfaces</title>
<link rel="stylesheet" type="text/css" href="styles.css"></link>
<script src="clean_pre.js"></script>
</head>
<body>
<h1>fluent interfaces</h1>
<h2>description</h2>
<p>Context being passed through method chaining</p>
<h2>methods</h2>
<ul>
<li>
<p>return value of a called method: self referential, where new context is equivalent to the last context</p>
<h3>establishing profiles</h3>
<p>
<pre><code class='ruby'>
# Chaining of methods to create a profile
comes_in_rarely = CustomerProfile.new.frequency(5).monthly_spending(20)
# Methods will always return self
everyday = CustomerProfile.new.member.frequency(25).monthly_spending(500)
# CustomerProfile class
class CustomerProfile
def member
# do something
self
end
def frequency(times_per_month)
# do something
self
end
def monthly_spending(dollars)
# do something
self
end
end
</code></pre>
</p>
</li>
<li>wrappers nested or funtional specification</li>
</ul>
<h2>problems</h2>
<ul>
<li>
<p>Method chaining to only good for stateless object. If there's a need to add state to an object that's method chained, use wrappers to 'wrap' the state in.</p>
<p>
<pre><code class='ruby'>
# Problem: 'add' method in the chain will have a problem saving the object as the rest of the methods are not called yet
rule.add.CustomerProfile.new.frequency(5).monthly_spending(20)
# Solution: wrapping CustomerProfile object in the 'add' method
rule.add(CustomerProfile.new.frequency(5).monthly_spending(20))
def add(profile)
# do something
save
end
</code></pre>
</p>
</li>
</ul>
</body>
</html>