Permalink
Browse files

Merge pull request #7 from ryw/faster-all_followers

Faster all followers
  • Loading branch information...
2 parents 7e27e45 + 9b5eaa8 commit bc81b779870239bb8c163d0cc21e77e4c430269e @lastomato committed Oct 29, 2012
Showing with 148 additions and 165 deletions.
  1. +41 −3 lib/mongo_followable/followed.rb
  2. +96 −141 spec/mongo/followable_spec.rb
  3. +2 −14 spec/mongo/performance_spec.rb
  4. +7 −0 spec/mongoid.yml
  5. +2 −7 spec/spec_helper.rb
@@ -106,8 +106,46 @@ def followed?
# >> @ruby.all_followers
# => [@jim]
- def all_followers
- rebuild_instances(self.followers)
+ def all_followers(page = nil, per_page = nil)
+ pipeline = [
+ { '$project' =>
+ { _id: 0,
+ f_id: 1,
+ followable_id: 1,
+ followable_type: 1
+ }
+ },
+ {
+ '$match' => {
+ 'followable_id' => self.id,
+ 'followable_type' => self.class.name.split('::').last
+ }
+ }
+ ]
+
+ if page && per_page
+ pipeline << { '$skip' => (page * per_page) }
+ pipeline << { '$limit' => per_page }
+ end
+
+ pipeline << { '$project' => { f_id: 1 } }
+
+ command = {
+ aggregate: 'follows',
+ pipeline: pipeline
+ }
+
+ if defined?(Mongoid)
+ db = Mongoid.default_session
+ elsif defined?(MongoMapper)
+ db = MongoMapper.database
+ end
+
+ users_hash = db.command(command)['result']
+
+ ids = users_hash.map {|e| e['f_id']}
+
+ User.where(id: { '$in' => ids }).all.entries
end
def unfollowed(*models, &block)
@@ -190,4 +228,4 @@ def rebuild_instances(follows) #:nodoc:
end
end
end
-end
+end
Oops, something went wrong.

0 comments on commit bc81b77

Please sign in to comment.