Class: Paginator

Inherits:
Object
  • Object
show all
Defined in:
lib/paginator.rb

Constant Summary

VERSION =
'0.1.0'

Instance Method Summary (collapse)

Constructor Details

- (Paginator) initialize(collection, per_page = 10)

Returns an instance of Paginator.

Parameters:

  • collection (Array)

    The Array-like object you want to paginate.

  • per_page (Fixnum) (defaults to: 10)

    The number of objects you want grouped per page.



8
9
10
11
# File 'lib/paginator.rb', line 8

def initialize collection, per_page = 10
  @collection = collection
  @per_page   = per_page
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

- (Object) method_missing(method, *args, &block)



36
37
38
39
40
41
42
43
44
45
46
# File 'lib/paginator.rb', line 36

def method_missing method, *args, &block
  if @collection.respond_to? method
    singleton_class.instance_eval do
      define_method(method) { |*args, &block|  @collection.send method, *args, &block }
    end

    @collection.send method, *args, &block
  else
    super
  end
end

Instance Method Details

- (Array<Object>) page(page)

Returns an array of objects for page.

Parameters:

  • page (Fixnum)

    The page number you'd like to request.

Returns:

  • (Array<Object>)

    Returns an array of objects for page.

See Also:



16
17
18
19
20
# File 'lib/paginator.rb', line 16

def page page
  startpoint = (@per_page * page) - @per_page 
  endpoint   = (@per_page * page) - 1
  @collection[startpoint..endpoint]
end

- (Range) pages

The total number of paginated pages.

Returns:

  • (Range)

    The total number of paginated pages.

See Also:



24
25
26
27
28
29
30
31
32
33
34
# File 'lib/paginator.rb', line 24

def pages
  remainder = @collection.size % @per_page 
  
  if @collection.size == 0
    1..1
  elsif remainder == 0
    1..@collection.size / @per_page
  elsif remainder > 0
    1..(@collection.size / @per_page) + 1
  end
end

- (Boolean) respond_to?(method, with_private = false)

Returns:

  • (Boolean)


48
49
50
# File 'lib/paginator.rb', line 48

def respond_to? method, with_private = false
  super || @collection.respond_to?(method, with_private)
end