blank_slate fix for Rails < 2.x; cap recipe
[acts_as_ferret.git] / lib / search_results.rb
blob5a5f131adc9b3c18cf9e730c3a14530cb42732d2
1 module ActsAsFerret
3   # decorator that adds a total_hits accessor and will_paginate compatible 
4   # paging support to search result arrays
5   class SearchResults < ActsAsFerret::BlankSlate
6     reveal :methods
7     attr_reader :current_page, :per_page, :total_hits
8     alias total_entries total_hits  # will_paginate compatibility
10     def initialize(results, total_hits, current_page = 1, per_page = nil)
11       @results = results
12       @total_hits = total_hits
13       @current_page = current_page
14       @per_page = (per_page || total_hits)
15       @total_pages   = @per_page > 0 ? (@total_hits / @per_page.to_f).ceil : 0
16     end
18     def method_missing(symbol, *args, &block)
19       @results.send(symbol, *args, &block)
20     end
22     def respond_to?(name)
23       methods.include?(name.to_s) || @results.respond_to?(name)
24     end
27     # code from here on was directly taken from will_paginate's collection.rb
29     #
30     # The total number of pages.
31     def page_count
32       @total_pages
33     end
35     # Current offset of the paginated collection. If we're on the first page,
36     # it is always 0. If we're on the 2nd page and there are 30 entries per page,
37     # the offset is 30. This property is useful if you want to render ordinals
38     # besides your records: simply start with offset + 1.
39     #
40     def offset
41       (current_page - 1) * per_page
42     end
44     # current_page - 1 or nil if there is no previous page
45     def previous_page
46       current_page > 1 ? (current_page - 1) : nil
47     end
49     # current_page + 1 or nil if there is no next page
50     def next_page
51       current_page < page_count ? (current_page + 1) : nil
52     end
53   end
55 end