Skip to content

Instantly share code, notes, and snippets.

@david
Created August 19, 2012 19:48
Show Gist options
  • Save david/3397247 to your computer and use it in GitHub Desktop.
Save david/3397247 to your computer and use it in GitHub Desktop.
class PersistentCollection
def initialize(klass)
@klass = klass
end
# ...
end
# This should be reusable
class ScopedCollection
def initialize(collection, scope = IdentityScope.new)
@collection = collection
@scope = scope
super @collection
end
def each(&block)
@scope.on_read(@collection).each &block
self
end
def <<(e)
@scope.on_write e
@collection << e
self
end
end
# This is the business-specific part
class PublishedPostScope
def initialize(publisher)
@publisher = publisher
end
def on_read(collection)
collection.where('published_at is not null and publisher_id = ?', publisher.id)
end
def on_write(post)
post.published_at = Time.now
post.publisher = @publisher
end
end
# And this is how you use it
pp = ScopedCollection.new(PersistentCollection.new(Post), PublishedPostScope.new(current_user))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment