Rails 2.3.5
I have a report being created on 3 different views (main, pre-view, and a layout-free plain HTML version for an auto email). The report uses about 28 queries and for some of those queries I’m doing some logic before the query:
sunday_this_week = (Time.now.beginning_of_week - 1.days).strftime("%Y-%m-%d")
sunday_1_week_ago = (Time.now.beginning_of_week - 8.days).strftime("%Y-%m-%d")
sunday_2_week_ago = (Time.now.beginning_of_week - 15.days).strftime("%Y-%m-%d")
sunday_3_week_ago = (Time.now.beginning_of_week - 22.days).strftime("%Y-%m-%d")
sunday_4_week_ago = (Time.now.beginning_of_week - 29.days).strftime("%Y-%m-%d")
@sunday_dates = [sunday_this_week,sunday_1_week_ago,sunday_2_week_ago,sunday_3_week_ago,sunday_4_week_ago ]
sql = %Q{
SELECT * FROM report_notes
WHERE week_of IN(?)
ORDER BY week_of ASC, market ASC, measure ASC
}
@performance_metric_notes = RptNote.find_by_sql([ sql, @sunday_dates ])
Some of the queries are really large and since 3 views need them, I have the same queries listed under three differenct controller mthods. There’s a lot of lines in the controller (~1400 lines).
What would you do to refactor something like ( is it possible to have a single controller method with all the query setup logic and queries, that the 3 different view methods can call instead of each view method having a copy )?
Thanks!
I would extract all of this code in a separate
Reportclass.Moving it to another controller action would still result in a huge controller. Plus, if there is a lot of logic to generate the report, the controller action is not the right place for it. It’s a lot better if you can keep your controllers clean, just preparing variables for the views.
Just put your class in /lib, and in your controller actions you can call something like
You get the idea.