Skip to content

Instantly share code, notes, and snippets.

@hannesg
Created November 29, 2010 22:27
Show Gist options
  • Save hannesg/720764 to your computer and use it in GitHub Desktop.
Save hannesg/720764 to your computer and use it in GitHub Desktop.
class User
include Splash::Document
end
users = Scope.new(User, {:query=>{'posts'=>{'$gt'=> 10 }}}) # <- users now behaves very similiar to User, except that it only finds users with >= 10 posts
users2 = User.query({'posts'=>{'$gt'=> 10 }}) # <- shorthand for the above
users3 = users.query('tags'=>'cool guy') # <- scopes are stackable. users3 now finds all users with >= 10 posts and tag 'cool guy'
class User
include Splash::Document
module ScopedMethods
def print_users!
self.each do |u|
puts u.inspect
end
return self
end
end
# extends User and all derived scopes with ScopedMethods
extend_scoped! ScopedMethods
# extends User and all derived scopes with these methods
extend_scoped! do
def cool
conditions('cool'=>true)
end
end
end
def print_users(users)
users.all.each do |user|
puts user.inspect
end
end
class User < ActiveRecord::Base
named_scope :with_more_posts_than, lambda{|posts| {:conditions=>['posts >= ?',posts]} }
def self.print_users!
print_users(self) # <- this access is scoped as expected
return self # <- self is in this case everytime User !
end
end
print_users( User ) # <- prints all users
print_users( User.with_more_posts_than(5) ) # <- prints all users with >= 5 posts
print_users( User.print_users! ) # <- prints all users twice
print_users( User.with_more_posts_than(5).print_users! ) # <- prints all users with >= 5 posts and then all users!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment