[英]How to refactor this Ruby (controller) code?
這是我的報表控制器中的代碼,看起來太糟糕了,有人可以給我一些整理建議嗎?
# app\controller\reports_controller.rb
@report_lines = []
@sum_wp, @sum_projcted_wp, @sum_il, @sum_projcted_il, @sum_li,@sum_gross_profit ,@sum_opportunities = [0,0,0,0,0,0,0]
date = @start_date
num_of_months.times do
wp,projected_wp, invoice_line,projected_il,line_item, opp = Report.data_of_invoicing_and_delivery_report(@part_or_service,date)
@sum_wp += wp
@sum_projcted_wp +=projected_wp
@sum_il=invoice_line
@sum_projcted_il +=projected_il
@sum_li += line_item
gross_profit = invoice_line - line_item
@sum_gross_profit += gross_profit
@sum_opportunities += opp
@report_lines << [date.strftime("%m/%Y"),wp,projected_wp ,invoice_line,projected_il,line_item,gross_profit,opp]
date = date.next_month
end
我正在尋找使用類似的方法
@sum_a,@sum_b,@sum_c += [1,2,3]
我立即想到的是:將代碼移至模型。
目標應該是“瘦控制器”,因此它們不應包含業務邏輯。
其次,我想將報表行作為OpenStruct()對象呈現給我的視圖,這對我來說似乎更干凈。
因此,我考慮將這種累加邏輯移到(很可能是)Report的類方法中,並返回“報告行” OpenStructs數組和單個合計OpenStruct傳遞給我的View。
我的控制器代碼將變成這樣:
@report_lines, @report_totals = Report.summarised_data_of_inv_and_dlvry_rpt(@part_or_service, @start_date, num_of_months)
編輯:(一天后)
看着添加到數組中的東西,我想到了這個:
require 'test/unit'
class Array
def add_corresponding(other)
each_index { |i| self[i] += other[i] }
end
end
class TestProblem < Test::Unit::TestCase
def test_add_corresponding
a = [1,2,3,4,5]
assert_equal [3,5,8,11,16], a.add_corresponding([2,3,5,7,11])
assert_equal [2,3,6,8,10], a.add_corresponding([-1,-2,-2,-3,-6])
end
end
看:測試! 看來工作正常。 沒有檢查兩個數組之間的大小差異,因此有很多方法可能出錯,但是這個概念聽起來很合理。 我正在考慮嘗試類似的方法,使我可以采用ActiveRecord結果集並將其累積到OpenStruct中,這就是我傾向於在報表中使用的結果集...
我們新的Array方法可能會將原始代碼簡化為以下形式:
totals = [0,0,0,0,0,0,0]
date = @start_date
num_of_months.times do
wp, projected_wp, invoice_line, projected_il, line_item, opp = Report.data_of_invoicing_and_delivery_report(@part_or_service,date)
totals.add_corresponding [wp, projected_wp, invoice_line, projected_il, line_item, opp, invoice_line - line_item]
@report_lines << [date.strftime("%m/%Y"),wp,projected_wp ,invoice_line,projected_il,line_item,gross_profit,opp]
date = date.next_month
end
@sum_wp, @sum_projcted_wp, @sum_il, @sum_projcted_il, @sum_li, @sum_opportunities, @sum_gross_profit = totals
...如果Report#data_of_invoicing_and_delivery_report也可以計算gross_profit
則將進一步減少至:
num_of_months.times do
totals.add_corresponding(Report.data_of_invoicing_and_delivery_report(@part_or_service,date))
end
完全未經測試,但這對於在Array中添加單行方法並在模型中執行一次額外的減法是一件令人費解的事情。
創建一個包含所有這些字段的求和對象,將整個數組傳遞給@ sum.increment_sums(Report.data_of ...)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.