ankane/groupdate — pull request #47 by trestrantham (2014-06-14 04:15:16+00:00)
Title: Allow a model to define its own database calculations via `to_groupdate`

I have a use case where I am defining custom calculations using database aggregate functions manually rather than via `ActiveRecord::Calculations`. Allowing the ability to define a custom `to_groupdate` function that handles serialization would allow using the groupdate (and chartkick!) with any arbitrary calculation.

My `to_groupdate` method is defined like so on any applicable model where `group` maps to a groupdate interval alias like `:day`, `:week`, or `:month` and `attribute` is the alias I've given my custom calculation:

```ruby
def self.to_groupdate(group, attribute)
Hash[all.to_a.map { |x| [x[group.to_s], x[attribute.to_s]] }]
end
```

This change would add `to_groupdate` to what is currently a list of `ActiveRecord::Calculation` methods as methods available for delegation to the `Groupdate::Series`'s underlying `@relation` and would be entirely opt-in.

A calculation that calls `to_groupdate` might be defined like below. Note: we have to capture the generated interval column and re-add it to the scope because specifying `select` clobbers any existing select clauses.

```ruby
scope = User.group_by_month(:created_at)
group_column = scope.relation.group_values.first
scope.select("(SUM(logins) / AVG(age)) AS login_age_ratio, #{group_column} AS month").to_groupdate(:month, :login_age_ratio)
```

If this would be a direction you're willing to consider, I can provide more examples and some appropriate tests if desired.