Skip to content

Commit

Permalink
Use keyword arguments
Browse files Browse the repository at this point in the history
  • Loading branch information
ankane committed Oct 7, 2016
1 parent 2c06f56 commit 0d31a28
Show file tree
Hide file tree
Showing 3 changed files with 16 additions and 10 deletions.
4 changes: 4 additions & 0 deletions CHANGELOG.md
@@ -1,3 +1,7 @@
## 0.2.0 [unreleased]

- Use keyword arguments

## 0.1.4

- Added `distinct` option to replace `uniq`
Expand Down
16 changes: 6 additions & 10 deletions lib/hightop.rb
Expand Up @@ -2,27 +2,23 @@
require "active_record"

module Hightop
def top(column, limit = nil, options = {})
if limit.is_a?(Hash)
options = limit
limit = nil
end

distinct = options[:distinct] || options[:uniq]
def top(column, limit = nil, distinct: nil, uniq: nil, min: nil, nil: nil)
distinct ||= uniq
order_str = column.is_a?(Array) ? column.map(&:to_s).join(", ") : column
relation = group(column).order("count_#{distinct || 'all'} DESC, #{order_str}")
if limit
relation = relation.limit(limit)
end

unless options[:nil]
# terribly named option
unless binding.local_variable_get(:nil)
(column.is_a?(Array) ? column : [column]).each do |c|
relation = relation.where("#{c} IS NOT NULL")
end
end

if options[:min]
relation = relation.having("COUNT(#{distinct ? "DISTINCT #{distinct}" : '*'}) >= #{options[:min].to_i}")
if min
relation = relation.having("COUNT(#{distinct ? "DISTINCT #{distinct}" : '*'}) >= #{min.to_i}")
end

if distinct
Expand Down
6 changes: 6 additions & 0 deletions test/hightop_test.rb
Expand Up @@ -101,6 +101,12 @@ def test_min_distinct
assert_equal expected, Visit.top(:city, min: 2, distinct: :user_id)
end

def test_bad_argument
assert_raises(ArgumentError) do
Visit.top(:city, boom: true)
end
end

def create_city(city, count = 1)
create({city: city}, count)
end
Expand Down

0 comments on commit 0d31a28

Please sign in to comment.