一段代码的重构

第一次

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
def update_encourage_count!
thanks = [[*0..2], [*1..5]]
hugs = [[*0..3], [*1..5]]
handclaps = [[*0..5], [*2..7]]
if votes.exists?
choiced_thanks = thanks[1]
choiced_hugs = hugs[1]
choiced_handclaps = handclaps[1]
else
choiced_thanks = thanks[0]
choiced_hugs = hugs[0]
choiced_handclaps = handclaps[0]
end
self.thanks_count = thanks_count.to_i + choiced_thanks.sample
self.hugs_count = hugs_count.to_i + choiced_hugs.sample
self.handclaps_count = handclaps_count.to_i + choiced_handclaps.sample
save!
end

第二次

1
2
3
4
5
6
7
8
9
10
11
12
def update_encourage_count!
thanks = [[*0..2], [*1..5]]
hugs = [[*0..3], [*1..5]]
handclaps = [[*0..5], [*2..7]]
choiced_thanks = votes.exists? ? thanks[1] : thanks[0]
choiced_hugs = votes.exists? ? hugs[1] : hugs[0]
choiced_handclaps = votes.exists? ? handclaps[1] : handclaps[0]
self.thanks_count = thanks_count.to_i + choiced_thanks.sample
self.hugs_count = hugs_count.to_i + choiced_hugs.sample
self.handclaps_count = handclaps_count.to_i + choiced_handclaps.sample
save!
end

第三次

1
2
3
4
5
6
7
def update_encourage_count!(thanks = [[*0..2], [*1..5]], hugs = [[*0..3], [*1..5]], handclaps = [[*0..5], [*2..7]])
choiced_thanks, choiced_hugs, choiced_handclaps = votes.exists? ? [thanks[1], hugs[1], handclaps[1]] : [thanks[0], hugs[0], handclaps[0]]
self.thanks_count = thanks_count.to_i + choiced_thanks.sample
self.hugs_count = hugs_count.to_i + choiced_hugs.sample
self.handclaps_count = handclaps_count.to_i + choiced_handclaps.sample
save!
end