Browse Source

Merge branch 'feature-paginated' of cli/Chronobriq-API into master

Lou 3 years ago
parent
commit
e009857e2e
3 changed files with 68 additions and 1 deletions
  1. 13
    0
      app/models/paginated.rb
  2. 54
    0
      test/models/paginated_test.rb
  3. 1
    1
      test/test_helper.rb

+ 13
- 0
app/models/paginated.rb View File

1
+module Paginated
2
+  DEFAULT_COUNT_BY_PAGE = 10
3
+  # can be overwritten
4
+  def count_by_page
5
+    DEFAULT_COUNT_BY_PAGE
6
+  end
7
+
8
+  def paginate(params)
9
+    page = (params.fetch :page, 0).to_i
10
+    start = page * count_by_page
11
+    offset(start).limit(count_by_page)
12
+  end
13
+end

+ 54
- 0
test/models/paginated_test.rb View File

1
+require "test_helper"
2
+require_relative "../../app/models/paginated"
3
+
4
+class FakePaginated
5
+  include Paginated
6
+  DATA = ("a".."z").to_a
7
+
8
+  # fake inspection
9
+  attr_reader :data
10
+
11
+  # fake a model
12
+  def initialize
13
+    @data = DATA
14
+  end
15
+
16
+  # fake a model
17
+  def offset(start)
18
+    @data = @data[start..]
19
+    self
20
+  end
21
+
22
+  # fake a model
23
+  def limit(count)
24
+    @data = @data[...count]
25
+    self
26
+  end
27
+
28
+  def count_by_page
29
+    3
30
+  end
31
+end
32
+
33
+class PaginatedTest < ActiveSupport::TestCase
34
+  def assert_valid_pagination(paginated, count:)
35
+    assert_equal count, paginated.data.size
36
+  end
37
+
38
+  test "paginated with placeholder" do
39
+    test_empty_params = FakePaginated.new.paginate({})
40
+    assert_valid_pagination test_empty_params, count: FakePaginated.new.count_by_page
41
+    assert_equal %w[a b c], test_empty_params.data
42
+
43
+    test_valid_params = FakePaginated.new.paginate({ page: 1 })
44
+    assert_valid_pagination test_valid_params, count: FakePaginated.new.count_by_page
45
+    assert_equal %w[d e f], test_valid_params.data
46
+    test_valid_params = FakePaginated.new.paginate({ page: 4 })
47
+    assert_valid_pagination test_valid_params, count: FakePaginated.new.count_by_page
48
+    assert_equal %w[m n o], test_valid_params.data
49
+
50
+    test_invalid_params = FakePaginated.new.paginate({ page: "what" })
51
+    assert_valid_pagination test_invalid_params, count: FakePaginated.new.count_by_page
52
+    assert_equal %w[a b c], test_invalid_params.data
53
+  end
54
+end

+ 1
- 1
test/test_helper.rb View File

10
   fixtures :all
10
   fixtures :all
11
 
11
 
12
   # Add more helper methods to be used by all tests here...
12
   # Add more helper methods to be used by all tests here...
13
-end
13
+end

Loading…
Cancel
Save