• Stars
    star
    3,617
  • Rank 11,643 (Top 0.3 %)
  • Language
    Ruby
  • License
    MIT License
  • Created almost 11 years ago
  • Updated 7 months ago

Reviews 5.0 (1)

9 months ago by Igor Kasyanchuk

Very useful gem, along with many other gems created by ankane. Worth to check them all.

Repository Details

The simplest way to group temporal data

Groupdate

The simplest way to group by:

  • day
  • week
  • hour of the day
  • and more (complete list below)

πŸŽ‰ Time zones - including daylight saving time - supported!! the best part

🍰 Get the entire series - the other best part

Supports PostgreSQL, MySQL, and Redshift, plus arrays and hashes (and limited support for SQLite)

πŸ’˜ Goes hand in hand with Chartkick

Build Status

Installation

Add this line to your application’s Gemfile:

gem "groupdate"

For MySQL and SQLite, also follow these instructions.

Getting Started

User.group_by_day(:created_at).count
# {
#   Sat, 24 May 2020 => 50,
#   Sun, 25 May 2020 => 100,
#   Mon, 26 May 2020 => 34
# }

Results are returned in ascending order by default, so no need to sort.

You can group by:

  • second
  • minute
  • hour
  • day
  • week
  • month
  • quarter
  • year

and

  • minute_of_hour
  • hour_of_day
  • day_of_week (Sunday = 0, Monday = 1, etc)
  • day_of_month
  • day_of_year
  • month_of_year

Use it anywhere you can use group. Works with count, sum, minimum, maximum, and average. For median and percentile, check out ActiveMedian.

Time Zones

The default time zone is Time.zone. Change this with:

Groupdate.time_zone = "Pacific Time (US & Canada)"

or

User.group_by_week(:created_at, time_zone: "Pacific Time (US & Canada)").count
# {
#   Sun, 08 Mar 2020 => 70,
#   Sun, 15 Mar 2020 => 54,
#   Sun, 22 Mar 2020 => 80
# }

Time zone objects also work. To see a list of available time zones in Rails, run rake time:zones:all.

Week Start

Weeks start on Sunday by default. Change this with:

Groupdate.week_start = :monday

or

User.group_by_week(:created_at, week_start: :monday).count

Day Start

You can change the hour days start with:

Groupdate.day_start = 2 # 2 am - 2 am

or

User.group_by_day(:created_at, day_start: 2).count

Time Range

To get a specific time range, use:

User.group_by_day(:created_at, range: 2.weeks.ago.midnight..Time.now).count

To expand the range to the start and end of the time period, use:

User.group_by_day(:created_at, range: 2.weeks.ago..Time.now, expand_range: true).count

To get the most recent time periods, use:

User.group_by_week(:created_at, last: 8).count # last 8 weeks

To exclude the current period, use:

User.group_by_week(:created_at, last: 8, current: false).count

Order

You can order in descending order with:

User.group_by_day(:created_at, reverse: true).count

Keys

Keys are returned as date or time objects for the start of the period.

To get keys in a different format, use:

User.group_by_month(:created_at, format: "%b %Y").count
# {
#   "Jan 2020" => 10
#   "Feb 2020" => 12
# }

or

User.group_by_hour_of_day(:created_at, format: "%-l %P").count
# {
#    "12 am" => 15,
#    "1 am"  => 11
#    ...
# }

Takes a String, which is passed to strftime, or a Symbol, which is looked up by I18n.localize in i18n scope 'time.formats', or a Proc. You can pass a locale with the locale option.

Series

The entire series is returned by default. To exclude points without data, use:

User.group_by_day(:created_at, series: false).count

Or change the default value with:

User.group_by_day(:created_at, default_value: "missing").count

Dynamic Grouping

User.group_by_period(:day, :created_at).count

Limit groupings with the permit option.

User.group_by_period(params[:period], :created_at, permit: ["day", "week"]).count

Raises an ArgumentError for unpermitted periods.

Custom Duration

To group by a specific number of minutes or seconds, use:

User.group_by_minute(:created_at, n: 10).count # 10 minutes

Date Columns

If grouping on date columns which don’t need time zone conversion, use:

User.group_by_week(:created_on, time_zone: false).count

Default Scopes

If you use Postgres and have a default scope that uses order, you may get a column must appear in the GROUP BY clause error (just like with Active Record’s group method). Remove the order scope with:

User.unscope(:order).group_by_day(:count).count

Arrays and Hashes

users.group_by_day { |u| u.created_at } # or group_by_day(&:created_at)

Supports the same options as above

users.group_by_day(time_zone: time_zone) { |u| u.created_at }

Get the entire series with:

users.group_by_day(series: true) { |u| u.created_at }

Count

users.group_by_day { |u| u.created_at }.to_h { |k, v| [k, v.count] }

Additional Instructions

For MySQL

Time zone support must be installed on the server.

mysql_tzinfo_to_sql /usr/share/zoneinfo | mysql -u root mysql

You can confirm it worked with:

SELECT CONVERT_TZ(NOW(), '+00:00', 'Pacific/Honolulu');

It should return the time instead of NULL.

For SQLite

Groupdate has limited support for SQLite.

  • No time zone support
  • No day_start option
  • No group_by_quarter method

If your application’s time zone is set to something other than Etc/UTC (the default), create an initializer with:

Groupdate.time_zone = false

Upgrading

6.0

Groupdate 6.0 protects against unsafe input by default. For non-attribute arguments, use:

User.group_by_day(Arel.sql(known_safe_value)).count

Also, the dates option has been removed.

History

View the changelog

Contributing

Everyone is encouraged to help improve this project. Here are a few ways you can help:

To get started with development and testing, check out the Contributing Guide.

More Repositories

1

pghero

A performance dashboard for Postgres
Ruby
7,123
star
2

searchkick

Intelligent search made easy
Ruby
6,257
star
3

chartkick

Create beautiful JavaScript charts with one line of Ruby
Ruby
6,157
star
4

blazer

Business intelligence made simple
Ruby
4,351
star
5

ahoy

Simple, powerful, first-party analytics for Rails
Ruby
3,872
star
6

strong_migrations

Catch unsafe migrations in development
Ruby
3,662
star
7

pgsync

Sync data from one Postgres database to another
Ruby
2,787
star
8

the-ultimate-guide-to-ruby-timeouts

Timeouts for popular Ruby gems
Ruby
2,212
star
9

production_rails

Best practices for running Rails in production
1,975
star
10

dexter

The automatic indexer for Postgres
Ruby
1,491
star
11

lockbox

Modern encryption for Ruby and Rails
Ruby
1,290
star
12

chartkick.js

Create beautiful charts with one line of JavaScript
JavaScript
1,211
star
13

react-chartkick

Create beautiful JavaScript charts with one line of React
JavaScript
1,183
star
14

pretender

Log in as another user in Rails
Ruby
1,124
star
15

ahoy_email

First-party email analytics for Rails
Ruby
1,051
star
16

secure_rails

Rails security best practices
954
star
17

pgslice

Postgres partitioning as easy as pie
Ruby
953
star
18

mailkick

Email subscriptions for Rails
Ruby
847
star
19

vue-chartkick

Create beautiful JavaScript charts with one line of Vue
JavaScript
747
star
20

eps

Machine learning for Ruby
Ruby
609
star
21

awesome-legal

Awesome free legal documents for companies
589
star
22

searchjoy

Search analytics made easy
Ruby
579
star
23

polars-ruby

Blazingly fast DataFrames for Ruby
Ruby
563
star
24

torch.rb

Deep learning for Ruby, powered by LibTorch
Ruby
552
star
25

blind_index

Securely search encrypted database fields
Ruby
470
star
26

safely

Rescue and report exceptions in non-critical code
Ruby
470
star
27

authtrail

Track Devise login activity
Ruby
466
star
28

ahoy.js

Simple, powerful JavaScript analytics
JavaScript
463
star
29

multiverse

Multiple databases for Rails πŸŽ‰
Ruby
463
star
30

hightop

A nice shortcut for group count queries
Ruby
462
star
31

field_test

A/B testing for Rails
Ruby
460
star
32

s3tk

A security toolkit for Amazon S3
Python
439
star
33

disco

Recommendations for Ruby and Rails using collaborative filtering
Ruby
431
star
34

active_median

Median and percentile for Active Record, Mongoid, arrays, and hashes
Ruby
427
star
35

informers

State-of-the-art natural language processing for Ruby
Ruby
417
star
36

notable

Track notable requests and background jobs
Ruby
402
star
37

shorts

Short, random tutorials and posts
379
star
38

tensorflow-ruby

Deep learning for Ruby
Ruby
350
star
39

distribute_reads

Scale database reads to replicas in Rails
Ruby
328
star
40

slowpoke

Rack::Timeout enhancements for Rails
Ruby
327
star
41

prophet-ruby

Time series forecasting for Ruby
Ruby
321
star
42

rover

Simple, powerful data frames for Ruby
Ruby
311
star
43

groupdate.sql

The simplest way to group temporal data
PLpgSQL
280
star
44

kms_encrypted

Simple, secure key management for Lockbox and attr_encrypted
Ruby
235
star
45

jetpack

A friendly package manager for R
R
234
star
46

neighbor

Nearest neighbor search for Rails and Postgres
Ruby
230
star
47

rollup

Rollup time-series data in Rails
Ruby
230
star
48

hypershield

Shield sensitive data in Postgres and MySQL
Ruby
227
star
49

logstop

Keep personal data out of your logs
Ruby
218
star
50

pdscan

Scan your data stores for unencrypted personal data (PII)
Go
213
star
51

delete_in_batches

Fast batch deletes for Active Record and Postgres
Ruby
202
star
52

vega-ruby

Interactive charts for Ruby, powered by Vega and Vega-Lite
Ruby
192
star
53

mapkick

Create beautiful JavaScript maps with one line of Ruby
Ruby
173
star
54

dbx

A fast, easy-to-use database library for R
R
171
star
55

fastText-ruby

Efficient text classification and representation learning for Ruby
Ruby
162
star
56

autosuggest

Autocomplete suggestions based on what your users search
Ruby
162
star
57

swipeout

Swipe-to-delete goodness for the mobile web
JavaScript
159
star
58

pghero.sql

Postgres insights made easy
PLpgSQL
154
star
59

mainstreet

Address verification for Ruby and Rails
Ruby
149
star
60

or-tools-ruby

Operations research tools for Ruby
Ruby
139
star
61

mapkick.js

Create beautiful, interactive maps with one line of JavaScript
JavaScript
138
star
62

trend-ruby

Anomaly detection and forecasting for Ruby
Ruby
128
star
63

mitie-ruby

Named-entity recognition for Ruby
Ruby
122
star
64

barkick

Barcodes made easy
Ruby
120
star
65

ownership

Code ownership for Rails
Ruby
111
star
66

anomaly

Easy-to-use anomaly detection for Ruby
Ruby
98
star
67

errbase

Common exception reporting for a variety of services
Ruby
87
star
68

tokenizers-ruby

Fast state-of-the-art tokenizers for Ruby
Rust
81
star
69

ip_anonymizer

IP address anonymizer for Ruby and Rails
Ruby
79
star
70

str_enum

String enums for Rails
Ruby
75
star
71

faiss-ruby

Efficient similarity search and clustering for Ruby
C++
73
star
72

trend-api

Anomaly detection and forecasting API
R
71
star
73

archer

Rails console history for Heroku, Docker, and more
Ruby
70
star
74

onnxruntime-ruby

Run ONNX models in Ruby
Ruby
70
star
75

xgboost-ruby

High performance gradient boosting for Ruby
Ruby
69
star
76

secure-spreadsheet

Encrypt and password protect sensitive CSV and XLSX files
JavaScript
66
star
77

active_hll

HyperLogLog for Rails and Postgres
Ruby
66
star
78

guess

Statistical gender detection for Ruby
Ruby
60
star
79

morph

An encrypted, in-memory, key-value store
C++
59
star
80

lightgbm

High performance gradient boosting for Ruby
Ruby
56
star
81

midas-ruby

Edge stream anomaly detection for Ruby
Ruby
54
star
82

moves

Ruby client for Moves
Ruby
54
star
83

blingfire-ruby

High speed text tokenization for Ruby
Ruby
54
star
84

vowpalwabbit-ruby

Fast online machine learning for Ruby
Ruby
52
star
85

xlearn-ruby

High performance factorization machines for Ruby
Ruby
51
star
86

tomoto-ruby

High performance topic modeling for Ruby
C++
51
star
87

trove

Deploy machine learning models in Ruby (and Rails)
Ruby
50
star
88

ahoy_events

Simple, powerful event tracking for Rails
Ruby
42
star
89

mapkick-static

Create beautiful static maps with one line of Ruby
Ruby
42
star
90

practical-search

Let’s make search a better experience for our users
40
star
91

breakout-ruby

Breakout detection for Ruby
Ruby
40
star
92

plu

Price look-up codes made easy
Ruby
40
star
93

ngt-ruby

High-speed approximate nearest neighbors for Ruby
Ruby
39
star
94

gindex

Concurrent index migrations for Rails
Ruby
39
star
95

clockwork_web

A web interface for Clockwork
Ruby
38
star
96

ahoy_guide

A foundation of knowledge and libraries for solid analytics
38
star
97

notable_web

A web interface for Notable
HTML
36
star
98

AnomalyDetection.rb

Time series anomaly detection for Ruby
Ruby
34
star
99

khiva-ruby

High-performance time series algorithms for Ruby
Ruby
34
star
100

immudb-ruby

Ruby client for immudb, the immutable database
Ruby
34
star