2009-06-03 65 views
0

這是我的報告控制器中的代碼,它看起來很糟糕,任何人都可以給我一些關於如何整理它的建議嗎?如何重構這個Ruby(控制器)代碼?

# 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] 

回答

5

我的瞬間想法是:將代碼移到模型中。

目標應該是「瘦控制器」,所以他們不應該包含業務邏輯。

其次,我喜歡將我的報告行作爲OpenStruct()對象呈現給我的視圖,這對我來說似乎更清晰。

所以我會考慮把這個積累邏輯移到Report上的一個類方法中,並返回一個「report line」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 

Look:a test!它似乎工作正常。沒有檢查兩個陣列之間的大小差異,所以有很多方法可能會出錯,但這個概念似乎足夠合理。我正在考慮嘗試類似的東西,讓我採用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 

......這要是報告#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 

完全未經測試,但是這對於一個下降的地獄將一行方法添加到數組中並在模型中執行單個額外減法。

+0

感謝您的提示,但是我正在尋找使用像 @ sum_a,@ sum_b,@ sum_c + = [1,2,3] 這個任何想法的一些方法? – 2009-06-03 08:45:19

2

創建一個包含所有這些領域的總和對象,整個數組傳遞給@ sum.increment_sums(Report.data_of ...)