I'm building an application that has a bunch of Monthly Total reports. Most of them are very similar and they are all working now but the code sucks. I have to clean this up and trying to figure out the best approach in doing so.
def active_monthly_total_by_type
respond_to do |format|
format.html
开发者_JAVA技巧 format.json {
@results = @current_account.items.totals_by_month(params[:selected_year], :status_change_date).with_type.active
render :json => @results.collect{ |result| { :type => result.type, :jan => result.jan, :feb => result.feb, :mar => result.mar, :apr => result.apr, :may => result.may, :jun => result.jun, :jul => result.jul, :aug => result.aug, :sep => result.sep, :oct => result.oct, :nov => result.nov, :dec => result.dec } }
}
end
end
def active_monthly_total
respond_to do |format|
format.html
format.json {
@results = @current_account.items.totals_by_month(params[:selected_year], :status_change_date).active
render :json => @results.collect{ |result| { :jan => result.jan, :feb => result.feb, :mar => result.mar, :apr => result.apr, :may => result.may, :jun => result.jun, :jul => result.jul, :aug => result.aug, :sep => result.sep, :oct => result.oct, :nov => result.nov, :dec => result.dec } }
}
I have 6 total methods like this and I'm trying to figure out if I pass it a param of active or inactive
params[:active]
if I can attach it to this call
@results = @current_account.items.totals_by_month(params[:selected_year], :status_change_date).params[:active]
if anyone can help or give me some advise where I can look for information I would love to have one method that controls all of these calls since they are the same. Here is the model scope:
def self.totals_by_month(year, date_type)
start_date = year.blank? ? Date.today.beginning_of_year : Date.parse("#{year}0101").beginning_of_year
end_date = year.blank? ? Date.today.end_of_year : Date.parse("#{year}0101").end_of_year
composed_scope = self.scoped
start_date.month.upto(end_date.month) do |month|
composed_scope = composed_scope.select("COUNT(CASE WHEN items.#{date_type.to_s} BETWEEN '#{start_date.beginning_of_month}' AND '#{start_date.end_of_month}' THEN 1 END) AS #{Date::ABBR_MONTHNAMES[month].downcase}")
start_date = start_date.next_month
end
composed_scope
end
I found a unique way to do this. I created a method called pie_chart and bar_chart which handles HTML and JSON for the requests and implemented this structure
/reports/:method/:year/:name/
send(params[:method],@current_account.items.send(params[:scope], params[:year]))
Where the URL would be /reports/pie_chart/2010/count_types_by_year
I have a pie_chart method in my controller and a count_types_by_year as the scope in my model and works like a charm Completely makes it dynamic and also makes it flexible for new additions...DRY baby DRY
精彩评论