15
acts_as_most_popular Wolfram Arnold RubyFocus

Acts As Most Popular

Embed Size (px)

DESCRIPTION

Presenting acts_as_most_popular: A plugin to cache most popular lists, such as most viewed videos, common to many social networking applications. acts_as_most_popular is built on top of Cache Money

Citation preview

Page 1: Acts As Most Popular

acts_as_most_popular

Wolfram ArnoldRubyFocus

Page 2: Acts As Most Popular

User Activity Tracking

Page 3: Acts As Most Popular

Join between:

Viewable entity (user profile, image, post, video ...)

Activity tracking(viewings, comments, ratings ...)

Page 4: Acts As Most Popular

Item.find(:all,

          :select => 'items.*,

             COUNT(*) AS viewing_count',

          :joins => :viewings, 

          :limit => limit,

          :group => 'viewings.item_id',

          :order => 'viewing_count DESC')

 

Page 5: Acts As Most Popular

acts_as_most_popularacts_as_most_popular

Page 6: Acts As Most Popular

acts_as_most_popular

I want:Most popular list from cache

Cache populared from database once

List automatically kept sorted & indexed in cache

I need:

A caching framework

Ideally something common, transparent & flexible

Page 7: Acts As Most Popular

Cache MoneyCache Money

Page 8: Acts As Most Popular

Cache Money

Transparent

find vs. get_cache

Sequence

AR Cache SQL

find → get → select

update → set → update

create → add → insert

destroy → delete/expire → delete

Maintains indices automatically!

Page 9: Acts As Most Popular

Cache Money

Instance methods on models:

get

set

repository

Automatic key handling

User.set(“new_key”)

→ Key: “User:1/new_key”

Page 10: Acts As Most Popular

SolutionSolution

Page 11: Acts As Most Popular

acts_as_most_popular

Additional index, sorted by activity count

primed on first access

maintained via after_add, after_remove callbacks

Page 12: Acts As Most Popular

Definition

class Item < ActiveRecord::Base

has_many :viewings

acts_as_most_popular \

:activity_association => :viewings,

:limit => 5,

:db_finder_args =>

{ :select => 'item_id,

COUNT(*) AS activity_count',

:group => 'item_id' }

end

Page 13: Acts As Most Popular

Usage

class StatsController < Application

def most_popular

@items = Item.most_popular

end

end

Page 14: Acts As Most Popular

References

Cache Money

http://magicscalingsprinkles.wordpress.com/2008/12/11/introducing-cache-money/

http://github.com/nkallen/cache-money/tree/master

Images

http://www.flickr.com/photos/flirtykitty/142229288/

http://www.flickr.com/photos/jojakeman/2434236126/

Page 15: Acts As Most Popular

Thank You!

Wolfram Arnold

RubyFocus

[email protected]