Skip to content

Instantly share code, notes, and snippets.

@kennethkalmer
Created February 8, 2010 20:02
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save kennethkalmer/298523 to your computer and use it in GitHub Desktop.
Save kennethkalmer/298523 to your computer and use it in GitHub Desktop.
class Announcement < CouchRest::ExtendedDocument
property :announcer
property :content
property :recipients, :cast_as => 'Array', :default => []
property :archived, :default => false, :type => :boolean
timestamps!
view_by :announcer_archive,
:map => "function( doc ) {
if( doc['couchrest-type'] == 'Announcement' && doc.archived ) {
emit( [ doc.announcer, doc.created_at ], 1 );
}
}",
:reduce => "function( keys, values, rereduce ) {
if( rereduce ) {
return sum( values );
}
else {
return values.length;
}
}"
class << self
def by_admins( archived = false, options = {} )
options[:page] ||= 1
options[:per_page] ||= 25
view_name = archived ? 'by_announcer_archive' : 'by_announcer'
WillPaginate::Collection.create( options[:page], options[:per_page] ) do |pager|
results = paginate(
options.merge(
:design_doc => 'Announcement', :view_name => view_name,
:startkey => ['admin', {}], :endkey => ['admin'],
:include_docs => true, :descending => true,
:reduce => false
)
)
pager.replace( results )
total = view( view_name, :startkey => ['admin'], :endkey => ['admin', {}], :reduce => true, :group_level => 1 )['rows'].pop
if total
pager.total_entries = total['value']
else
pager.total_entries = 0
end
end
end
end
end
class AnnouncementsController < ApplicationController
def index
pagination_options = { :page => params[:page], :per_page => params[:per_page] }
@announcements = Announcement.by_admins( params[:archived], pagination_options )
end
end
= will_paginate @announcements
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment