-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdynamic_methods.rb
116 lines (96 loc) · 2.13 KB
/
dynamic_methods.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
50
51
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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
class DS
def get_cpu_info
"Dual Core"
end
def get_cpu_price
100
end
def get_mouse_info
"Optical"
end
def get_mouse_price
200
end
def get_keyboard_info
"Zing"
end
def get_keyboard_price
890
end
end
class Computer
def initialize(computer_id, data_source)
@id = computer_id
@data_source = data_source
end
def mouse
info = @data_source.get_mouse_info
price = @data_source.get_mouse_price
result = "Mouse: #{info} ($#{price})"
return "*#{result}" if price >= 100
result
end
def cpu
info = @data_source.get_cpu_info
price = @data_source.get_cpu_price
result = "Mouse: #{info} ($#{price})"
return "*#{result}" if price >= 100
result
end
end
#instead use dynamic methods
class Computer
def initialize(computer_id, data_source)
@id = computer_id
@data_source = data_source
end
def mouse
component :mouse
end
def cpu
component :cpu
end
def component(name)
info = @data_source.send "get_#{name}_info"
price = @data_source.send "get_#{name}_price"
result = "#{name.to_s.capitalize}: #{info} ($#{price})"
return "*#{result}" if price >= 100
result
end
end
#do even better
class Computer
def initialize(computer_id, data_source)
@id = computer_id
@data_source = data_source
end
def self.define_component(name)
define_method(name) do
info = @data_source.send "get_#{name}_info"
price = @data_source.send "get_#{name}_price"
result = "#{name.to_s.capitalize}: #{info} ($#{price})"
return "*#{result}" if price >= 100
result
end
end
define_component :mouse
define_component :cpu
end
#doing EVEN BETTER by using introspection and removing the define components
#to dynamically grab new computer parts
class Computer
def initialize(computer_id, data_source)
@id = computer_id
@data_source = data_source
data_source.methods.grep(/^get_(.*)_info/) { Computer.define_component $1 }
end
def self.define_component(name)
define_method(name) do
info = @data_source.send "get_#{name}_info"
price = @data_source.send "get_#{name}_price"
result = "#{name.capitalize}: #{info} ($#{price})"
return "*#{result}" if price >= 100
result
end
end
end