Permalink
Browse files

Added distinct option to replace uniq

  • Loading branch information...
1 parent 00d8aab commit 7b1edb1014a1d5ca88ae04228bb91c01816817bb @ankane committed Feb 4, 2016
Showing with 32 additions and 4 deletions.
  1. +4 −0 CHANGELOG.md
  2. +1 −1 README.md
  3. +6 −3 lib/hightop.rb
  4. +21 −0 test/hightop_test.rb
View
@@ -1,3 +1,7 @@
+## 0.1.4 [unreleased]
+
+- Added `distinct` option to replace `uniq`
+
## 0.1.3
- Fixed `min` option with `uniq`
View
@@ -43,7 +43,7 @@ Visit.top("LOWER(referring_domain)")
And distinct
```ruby
-Visit.top(:city, uniq: :user_id)
+Visit.top(:city, distinct: :user_id)
```
And min count
View
@@ -8,8 +8,9 @@ def top(column, limit = nil, options = {})
limit = nil
end
+ distinct = options[:distinct] || options[:uniq]
order_str = column.is_a?(Array) ? column.map(&:to_s).join(", ") : column
- relation = group(column).order("count_#{options[:uniq] || 'all'} DESC, #{order_str}")
+ relation = group(column).order("count_#{distinct || 'all'} DESC, #{order_str}")
if limit
relation = relation.limit(limit)
end
@@ -21,10 +22,12 @@ def top(column, limit = nil, options = {})
end
if options[:min]
- relation = relation.having("COUNT(#{options[:uniq] ? "DISTINCT #{options[:uniq]}" : '*'}) >= #{options[:min].to_i}")
+ relation = relation.having("COUNT(#{distinct ? "DISTINCT #{distinct}" : '*'}) >= #{options[:min].to_i}")
end
- if options[:uniq]
+ if options[:distinct]
+ relation.distinct.count(options[:distinct])
+ elsif options[:uniq]
relation.uniq.count(options[:uniq])
else
relation.count
View
@@ -62,6 +62,15 @@ def test_expressions
assert_equal expected, Visit.top("LOWER(city)")
end
+ def test_distinct
+ create(city: "San Francisco", user_id: 1)
+ create(city: "San Francisco", user_id: 1)
+ expected = {
+ "San Francisco" => 1
+ }
+ assert_equal expected, Visit.top(:city, distinct: :user_id)
+ end
+
def test_uniq
create(city: "San Francisco", user_id: 1)
create(city: "San Francisco", user_id: 1)
@@ -80,6 +89,18 @@ def test_min
assert_equal expected, Visit.top(:city, min: 3)
end
+ def test_min_distinct
+ create(city: "San Francisco", user_id: 1)
+ create(city: "San Francisco", user_id: 1)
+ create(city: "San Francisco", user_id: 2)
+ create(city: "Chicago", user_id: 1)
+ create(city: "Chicago", user_id: 1)
+ expected = {
+ "San Francisco" => 2
+ }
+ assert_equal expected, Visit.top(:city, min: 2, distinct: :user_id)
+ end
+
def create_city(city, count = 1)
create({city: city}, count)
end

0 comments on commit 7b1edb1

Please sign in to comment.