我有一个具有 2 种方法的 Rails 控制器。两种方法都使用一些相同的变量,我想知道如何将其重构为控制器某处的模型中的任何一种方法,以使它们比现在更可重用。
class ChartsController < ApplicationController
before_filter :authenticate_user!, :company_id
def service_level
latest_date = Invoice.where(:account_id => @company.accounts).maximum(:invc_date)
invoices_filter = { :invoices => { :invc_date => (latest_date - 3.months)..latest_date } }
invoices = Invoice.where({:account_id => @company.accounts}.merge(invoices_filter))
details = InvoiceDetail.joins(:type).where(:invoice_id => invoices)
freight_details = details.where(:invoice_detail_types => { :category => 'freight' })
freight_groups = freight_details.group(:family).select("family, count(distinct package_id), sum(base_charge + discount)")
vol_data = {}
spend_data = {}
@charts = {}
@charts[:service_analysis] = {
:vol_data => Hash[freight_groups.map { |row| [InvoiceDetailFamily[row.family].name, row.count.to_i] }],
:spend_data => Hash[freight_groups.map { |row| [InvoiceDetailFamily[row.family].name, row.sum.to_f] }]
}
render partial: 'service_level'
end
def weight_summary
latest_date = Invoice.where(:account_id => @company.accounts).maximum(:invc_date)
invoices_filter = { :invoices => { :invc_date => (latest_date - 3.months)..latest_date } }
invoices = Invoice.where({:account_id => @company.accounts}.merge(invoices_filter))
details = InvoiceDetail.joins(:type).where(:invoice_id => invoices)
freight_details = details.where(:invoice_detail_types => { :category => 'freight' })
packages = freight_details.joins(:package, :invoice)
vol_data = {}
spend_data = {}
packages.group(:zone).select("zone, count(distinct package_id), sum(base_charge + discount)").each do |row|
case row.zone
when '02'..'08', '002'..'008', '102'..'108', '132'..'138', '202'..'208', '242'..'248', '302'..'308'
zg = row.zone[-1]
when '09'..'17', '124'..'126', '224'..'226'
zg = 'AK/HI/PR'
else
zg = 'Import/Export'
end
vol_data[zg] = (vol_data[zg] || 0) + row.count.to_i
spend_data[zg] = (spend_data[zg] || 0) + row.sum.to_f
end
@charts = {}
@charts[:weight_analysis] = {
:vol_data => Hash[(vol_data.sort_by {|key, value| key.scan(/\d+/)[0].to_i})],
:spend_data => Hash[(spend_data.sort_by {|key, value| key.scan(/\d+/)[0].to_i})]
}
render partial: 'weight_summary'
end
end