views:

49

answers:

1

In a Rails 3 app, I'm running a somewhat complex group_by and am curious if I can hide it away elsewhere, much like one can hide away ActiveRecord conditions in a scope. I realize group_by is an operation on an Enumerable, so scopes don't apply here, but my question is if there's a way to create a shorthand for this in a comparable way:

@launches_and_finales = Show.launches_and_finales.sort_by { |s| 
   (s.run_starts_on && 
   ((Date.today - 3.days)..(Date.today + 3.days)) === s.run_starts_on) ? 
   s.run_starts_on : s.run_ends_on }

Side note: I realize 3.days.ago..3.days.from_now would be more succinct, but there's a bug in Ruby 1.9.2 that triggers an endless loop when I use that.

+1  A: 

I think you can implement this using one of these two strategies:

  1. Wrap the logic within an association extension
  2. Rails 3's Arel could help you wrap that into a standard method call

    class Show

    def self.launches_and_finales

    where(["run_starts_on between ? and ? or ...", Time.now - 3.day, Time.now + 3.days])
    

    end

    end

Cesario
I hadn't thought about doing more complex logic at the Model layer. I must have only considered scopes with their limitations here, but of course I can just add a whole new method. I don't think 2 will do the trick though, since it's the more complex group_by that I'm after, not just the filter.
Joost Schuur