Module: PunchingBag::ActiveRecord::ClassMethods
- Defined in:
- lib/punching_bag/acts_as_punchable.rb
Constant Summary collapse
- DIRECTIONS =
{ asc: 'ASC', desc: 'DESC' }.freeze
- DEFAULT_DIRECTION =
:desc
Instance Method Summary collapse
-
#most_hit(since = nil, limit = 5) ⇒ Object
Note: this method will only return items if they have 1 or more hits.
-
#sort_by_popularity(direction = DEFAULT_DIRECTION) ⇒ Object
Note: this method will return all items with 0 or more hits direction: Symbol (:asc, or :desc).
Instance Method Details
#most_hit(since = nil, limit = 5) ⇒ Object
Note: this method will only return items if they have 1 or more hits
11 12 13 14 15 |
# File 'lib/punching_bag/acts_as_punchable.rb', line 11 def most_hit(since = nil, limit = 5) query = joins(:punches).group(Punch.arel_table[:punchable_type], Punch.arel_table[:punchable_id], arel_table[primary_key]) query = query.where('punches.average_time >= ?', since) unless since.nil? query.reorder(Arel.sql('SUM(punches.hits) DESC')).limit(limit) end |
#sort_by_popularity(direction = DEFAULT_DIRECTION) ⇒ Object
Note: this method will return all items with 0 or more hits direction: Symbol (:asc, or :desc)
19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 |
# File 'lib/punching_bag/acts_as_punchable.rb', line 19 def sort_by_popularity(direction = DEFAULT_DIRECTION) dir = DIRECTIONS.fetch( direction.to_s.downcase.to_sym, DIRECTIONS[DEFAULT_DIRECTION] ) query = joins( arel_table.join( Punch.arel_table, Arel::Nodes::OuterJoin ).on( Punch.arel_table[:punchable_id].eq( arel_table[primary_key] ).and( Punch.arel_table[:punchable_type].eq(name) ) ).join_sources.first ) query = query.group(arel_table[primary_key]) query.reorder(Arel.sql("SUM(punches.hits) #{dir}")) end |