rb_pager 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: bf018c14e4ab9b25829e3400dee85caa296f7fcbd4cbdd96020eff0c620c5beb
4
+ data.tar.gz: 5629f3891861dda8bc388adcf3fd8196ba569bfb408ed2377bf80d61b1144871
5
+ SHA512:
6
+ metadata.gz: 370e67a57d010703c5d75dc4c0378876a39ad06d72da1d018d63eff8fc5ead95dce518cc2e4312dcc6181ea0c454e511fce210925686e8325f5e5b5b578106c9
7
+ data.tar.gz: 293378b679c82b97df6a25c35105e2024f3e1a8ad835261de14694cc23ffc34720b919fc8e26df8b136d0b8cb56171ffaf924a9c2e20dcfdd88bf5fb39bc10f7
@@ -0,0 +1,11 @@
1
+ /.bundle/
2
+ /.yardoc
3
+ /_yardoc/
4
+ /coverage/
5
+ /doc/
6
+ /pkg/
7
+ /spec/reports/
8
+ /tmp/
9
+
10
+ # rspec failure tracking
11
+ .rspec_status
data/.rspec ADDED
@@ -0,0 +1,3 @@
1
+ --format documentation
2
+ --color
3
+ --require spec_helper
@@ -0,0 +1,6 @@
1
+ ---
2
+ language: ruby
3
+ cache: bundler
4
+ rvm:
5
+ - 2.6.5
6
+ before_install: gem install bundler -v 2.1.4
data/Gemfile ADDED
@@ -0,0 +1,7 @@
1
+ source "https://rubygems.org"
2
+
3
+ # Specify your gem's dependencies in pager.gemspec
4
+ gemspec
5
+
6
+ gem "rake", "~> 12.0"
7
+ gem "rspec", "~> 3.0"
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2020 BambangSinaga
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in
13
+ all copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+ THE SOFTWARE.
@@ -0,0 +1,70 @@
1
+
2
+ # Pager
3
+
4
+
5
+ Cursor-based pagination (aka keyset pagination) is a [common](https://slack.engineering/evolving-api-pagination-at-slack-1c1f644f8e12) [pagination strategy](https://www.citusdata.com/blog/2016/03/30/five-ways-to-paginate/) that avoids many of the pitfalls of “offset–limit” pagination.
6
+
7
+ For example, with offset–limit pagination, if an item from a prior page is deleted while the client is paginating, all subsequent results will be shifted forward by one. Therefore, when the client requests the next page, there’s one result that it will skip over and never see. Conversely, if a result is added to the list of results as the client is paginating, the client may see the same result multiple times, on different pages. Cursor-based pagination can prevent both of these possibilities.
8
+
9
+ Cursor-based pagination also performs better for large data sets under most implementations.
10
+
11
+ To support cursor-based pagination, this specification defines three query parameters `after`, `limit`, `sort`
12
+
13
+ ## Installation
14
+
15
+ Add this line to your application's Gemfile:
16
+
17
+ ```ruby
18
+ gem 'rb_pager'
19
+ ```
20
+
21
+ And then execute:
22
+
23
+ $ bundle install
24
+
25
+ Or install it yourself as:
26
+
27
+ $ gem install rb_pager
28
+
29
+ Add the [rb_pager.rb](https://github.com/BambangSinaga/rb_pager/blob/master/lib/config/rb_pager.rb)
30
+
31
+ If you use Rails, put it into the `config/initializers` dir
32
+
33
+ ## Usage
34
+
35
+ Once the gem installed on your project, usually you don't need to do anything.
36
+ The system use `Base64.strict_decode64` and `Base64.strict_encode64` for cursor values
37
+
38
+ ```ruby
39
+ # return first 20 employee records, by default limit set to 20
40
+ Employee.pager(after: nil)
41
+
42
+ # return first 15 employee records
43
+ Employee.pager(after: nil, limit: 15)
44
+
45
+ # return first 10 employee records order by created_at asc
46
+ # /employee?limit=10&sort=created_at
47
+ Employee.pager(after: nil, limit: 10, sort: 'created_at')
48
+
49
+ # return first 10 employee records order by created_at desc
50
+ # /employee?limit=10&sort=-created_at
51
+ Employee.pager(after: nil, limit: 10, sort: '-created_at')
52
+
53
+ # [order by non uniq column](https://engineering.shopify.com/blogs/engineering/pagination-relative-cursors)
54
+ # /employee?limit=10&sort=name,id
55
+ Employee.pager(after: nil, limit: 10, sort: 'name,id')
56
+ ```
57
+
58
+ ## Development
59
+
60
+ After checking out the repo, run `bin/setup` to install dependencies. Then, run `rake spec` to run the tests. You can also run `bin/console` for an interactive prompt that will allow you to experiment.
61
+
62
+ To install this gem onto your local machine, run `bundle exec rake install`. To release a new version, update the version number in `version.rb`, and then run `bundle exec rake release`, which will create a git tag for the version, push git commits and tags, and push the `.gem` file to [rubygems.org](https://rubygems.org).
63
+
64
+ ## Contributing
65
+
66
+ Bug reports and pull requests are welcome on GitHub at https://github.com/BambangSinaga/rb_pager. This project is intended to be a safe, welcoming space for collaboration, and contributors.
67
+
68
+ ## License
69
+
70
+ The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
@@ -0,0 +1,6 @@
1
+ require "bundler/gem_tasks"
2
+ require "rspec/core/rake_task"
3
+
4
+ RSpec::Core::RakeTask.new(:spec)
5
+
6
+ task :default => :spec
@@ -0,0 +1,14 @@
1
+ #!/usr/bin/env ruby
2
+
3
+ require "bundler/setup"
4
+ require "pager"
5
+
6
+ # You can add fixtures and/or initialization code here to make experimenting
7
+ # with your gem easier. You can also use a different console, if you like.
8
+
9
+ # (If you use this, don't forget to add pry to your Gemfile!)
10
+ # require "pry"
11
+ # Pry.start
12
+
13
+ require "irb"
14
+ IRB.start(__FILE__)
@@ -0,0 +1,8 @@
1
+ #!/usr/bin/env bash
2
+ set -euo pipefail
3
+ IFS=$'\n\t'
4
+ set -vx
5
+
6
+ bundle install
7
+
8
+ # Do any other automated setup that you need to do here
@@ -0,0 +1,4 @@
1
+ # Pager.configure do |config|
2
+ # config.limit = 15
3
+ # config.max_limit = 100
4
+ # end
@@ -0,0 +1,21 @@
1
+ require 'active_record'
2
+ require 'rb_pager/version'
3
+ require "rb_pager/configuration"
4
+
5
+ module RbPager
6
+ class Error < StandardError; end
7
+
8
+ class << self
9
+ attr_accessor :configuration
10
+ end
11
+
12
+ def self.configure
13
+ self.configuration ||= Configuration.new
14
+ yield(configuration)
15
+ end
16
+ end
17
+
18
+ if defined?(ActiveRecord)
19
+ require 'rb_pager/orm/pager_active_record'
20
+ ActiveRecord::Base.send :include, RbPager::ActiveRecord
21
+ end
@@ -0,0 +1,14 @@
1
+ module RbPager
2
+ class Configuration
3
+ attr_accessor :limit, :max_limit
4
+
5
+ def initialize
6
+ @limit = 20
7
+ @max_limit = 100
8
+ end
9
+
10
+ def limit=(val)
11
+ @limit = [val, @max_limit].min
12
+ end
13
+ end
14
+ end
@@ -0,0 +1,133 @@
1
+ module RbPager
2
+ module ActiveRecord
3
+ extend ActiveSupport::Concern
4
+
5
+ module ClassMethods
6
+ AR_ORDER = { '+' => :asc, '-' => :desc }
7
+ AREL_ORDER = { asc: :gt, desc: :lt }
8
+
9
+ def pager(after:, limit: nil, sort: nil)
10
+ page_limit = limit || RbPager.configuration.limit
11
+ sort_params = sort
12
+ sorted_columns, sorter = build_order_expression(sort)
13
+ collection = if after.nil?
14
+ order(sorter).extending(ActiveRecordRelationMethods).limit(page_limit)
15
+ else
16
+ custom_expression = create_custom_expression(after, sorted_columns)
17
+ where(custom_expression).order(sorter).extending(ActiveRecordRelationMethods).limit(page_limit)
18
+ end
19
+
20
+ create_paginate_meta(collection, sorted_columns)
21
+ end
22
+
23
+ private
24
+
25
+ def create_custom_expression(cursor_params, sorted_columns)
26
+ decode_cursor_params = JSON.parse(Base64.strict_decode64(cursor_params))
27
+ return arel_table[primary_key].gt(decode_cursor_params[primary_key]) if sorted_columns.blank?
28
+
29
+ filter_ordered_columns = filter_with_ordered_columns(decode_cursor_params, sorted_columns)
30
+ filter_primary_key = filter_with_primary_key(decode_cursor_params)
31
+
32
+ filter_ordered_columns.or(filter_primary_key)
33
+ end
34
+
35
+ def filter_with_ordered_columns(decode_cursor_params, sorted_columns)
36
+ result = self
37
+ sorted_columns.each_with_index do |(column, type), index|
38
+ result = if index.zero?
39
+ result.arel_table[column].send(AREL_ORDER[type])
40
+ else
41
+ result.or(arel_table[column].send(AREL_ORDER[type]))
42
+ end
43
+ end
44
+
45
+ result
46
+ end
47
+
48
+ def filter_with_primary_key(decode_cursor_params)
49
+ result = self
50
+
51
+ decode_cursor_params.each_with_index do |(column, value), index|
52
+ result = if index.zero?
53
+ result.arel_table[column].gt(value)
54
+ else
55
+ result.and(arel_table[column].eq(value))
56
+ end
57
+ end
58
+
59
+ result
60
+ end
61
+
62
+ def build_order_expression(sort_params)
63
+ return {} if sort_params.nil?
64
+
65
+ sort_order = { '+' => 'ASC', '-' => 'DESC' }
66
+ sorted_params = {}
67
+ arel_orders = []
68
+
69
+ sort_params.split(',').each do |field|
70
+ next unless attribute_names.include?(field)
71
+
72
+ sort_sign = field =~ /\A[+-]/ ? field.slice!(0) : '+'
73
+ arel_orders << arel_table[field].send(AR_ORDER[sort_sign])
74
+ sorted_params[field] = AR_ORDER[sort_sign]
75
+ end
76
+
77
+ [sorted_params, arel_orders]
78
+ end
79
+
80
+ def create_paginate_meta(collection, sorted_columns)
81
+ next_cursor = next_cursor(collection, sorted_columns)
82
+
83
+ meta = { next_cursor: next_cursor }
84
+ [collection.to_a, meta]
85
+ end
86
+
87
+ def next_cursor(collection, sorted_columns)
88
+ return '' unless collection.left_over?
89
+
90
+ next_cursor = { 'id': collection.last.id }
91
+
92
+ sorted_columns.each do |key, _value|
93
+ next_cursor.merge!(Hash[key, collection.last.send(key)])
94
+ end
95
+
96
+ Base64.strict_encode64(next_cursor.to_json)
97
+ end
98
+ end
99
+
100
+ module ActiveRecordRelationMethods
101
+ def left_over?
102
+ @left_over ||= begin
103
+ # Cache #size otherwise multiple calls to the database will occur.
104
+ size.positive? && size < total_size
105
+ end
106
+ end
107
+
108
+ # Returns number of records that exist in scope of the current cursor
109
+ def total_size(column_name = :all) #:nodoc:
110
+ # #count overrides the #select which could include generated columns
111
+ # referenced in #order, so skip #order here, where it's irrelevant to the
112
+ # result anyway.
113
+ @total_size ||= begin
114
+ context = except(:offset, :limit, :order)
115
+
116
+ # Remove includes only if they are irrelevant
117
+ context = context.except(:includes) unless references_eager_loaded_tables?
118
+
119
+ args = [column_name]
120
+
121
+ # .group returns an OrderedHash that responds to #count
122
+ context = context.count(*args)
123
+
124
+ if context.is_a?(Hash) || context.is_a?(ActiveSupport::OrderedHash)
125
+ context.count
126
+ else
127
+ context.respond_to?(:count) ? context.count(*args) : context
128
+ end
129
+ end
130
+ end
131
+ end
132
+ end
133
+ end
@@ -0,0 +1,3 @@
1
+ module RbPager
2
+ VERSION = "0.1.0"
3
+ end
@@ -0,0 +1,34 @@
1
+ require_relative 'lib/rb_pager/version'
2
+
3
+ Gem::Specification.new do |spec|
4
+ spec.name = "rb_pager"
5
+ spec.version = RbPager::VERSION
6
+ spec.authors = ["BambangSinaga"]
7
+ spec.email = ["mejbambang@gmail.com"]
8
+
9
+ spec.summary = "Cursor based pagination for active_record currently"
10
+ spec.description = %q{ActiveRecord plugin for cursor based pagination for Ruby on Rails. \n
11
+ Cursor-based pagination (aka keyset pagination) is a common pagination strategy that avoids many of the pitfalls of “offset–limit” pagination.}
12
+ spec.homepage = "https://github.com/BambangSinaga/rb_pager"
13
+ spec.license = "MIT"
14
+ spec.required_ruby_version = Gem::Requirement.new(">= 2.3.0")
15
+
16
+ spec.metadata["allowed_push_host"] = "https://rubygems.org/"
17
+
18
+ spec.metadata["homepage_uri"] = spec.homepage
19
+ spec.metadata["source_code_uri"] = "https://github.com/BambangSinaga/rb_pager"
20
+ # spec.metadata["changelog_uri"] = "TODO: Put your gem's CHANGELOG.md URL here."
21
+
22
+ spec.add_development_dependency "sqlite3"
23
+ spec.add_development_dependency "activerecord"
24
+ spec.add_development_dependency "rspec"
25
+
26
+ # Specify which files should be added to the gem when it is released.
27
+ # The `git ls-files -z` loads the files in the RubyGem that have been added into git.
28
+ spec.files = Dir.chdir(File.expand_path('..', __FILE__)) do
29
+ `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) }
30
+ end
31
+ spec.bindir = "exe"
32
+ spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
33
+ spec.require_paths = ["lib"]
34
+ end
metadata ADDED
@@ -0,0 +1,105 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: rb_pager
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - BambangSinaga
8
+ autorequire:
9
+ bindir: exe
10
+ cert_chain: []
11
+ date: 2020-07-03 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: sqlite3
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - ">="
18
+ - !ruby/object:Gem::Version
19
+ version: '0'
20
+ type: :development
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - ">="
25
+ - !ruby/object:Gem::Version
26
+ version: '0'
27
+ - !ruby/object:Gem::Dependency
28
+ name: activerecord
29
+ requirement: !ruby/object:Gem::Requirement
30
+ requirements:
31
+ - - ">="
32
+ - !ruby/object:Gem::Version
33
+ version: '0'
34
+ type: :development
35
+ prerelease: false
36
+ version_requirements: !ruby/object:Gem::Requirement
37
+ requirements:
38
+ - - ">="
39
+ - !ruby/object:Gem::Version
40
+ version: '0'
41
+ - !ruby/object:Gem::Dependency
42
+ name: rspec
43
+ requirement: !ruby/object:Gem::Requirement
44
+ requirements:
45
+ - - ">="
46
+ - !ruby/object:Gem::Version
47
+ version: '0'
48
+ type: :development
49
+ prerelease: false
50
+ version_requirements: !ruby/object:Gem::Requirement
51
+ requirements:
52
+ - - ">="
53
+ - !ruby/object:Gem::Version
54
+ version: '0'
55
+ description: |-
56
+ ActiveRecord plugin for cursor based pagination for Ruby on Rails. \n
57
+ Cursor-based pagination (aka keyset pagination) is a common pagination strategy that avoids many of the pitfalls of “offset–limit” pagination.
58
+ email:
59
+ - mejbambang@gmail.com
60
+ executables: []
61
+ extensions: []
62
+ extra_rdoc_files: []
63
+ files:
64
+ - ".gitignore"
65
+ - ".rspec"
66
+ - ".travis.yml"
67
+ - Gemfile
68
+ - LICENSE.txt
69
+ - README.md
70
+ - Rakefile
71
+ - bin/console
72
+ - bin/setup
73
+ - lib/config/rb_pager.rb
74
+ - lib/rb_pager.rb
75
+ - lib/rb_pager/configuration.rb
76
+ - lib/rb_pager/orm/pager_active_record.rb
77
+ - lib/rb_pager/version.rb
78
+ - rb_pager.gemspec
79
+ homepage: https://github.com/BambangSinaga/rb_pager
80
+ licenses:
81
+ - MIT
82
+ metadata:
83
+ allowed_push_host: https://rubygems.org/
84
+ homepage_uri: https://github.com/BambangSinaga/rb_pager
85
+ source_code_uri: https://github.com/BambangSinaga/rb_pager
86
+ post_install_message:
87
+ rdoc_options: []
88
+ require_paths:
89
+ - lib
90
+ required_ruby_version: !ruby/object:Gem::Requirement
91
+ requirements:
92
+ - - ">="
93
+ - !ruby/object:Gem::Version
94
+ version: 2.3.0
95
+ required_rubygems_version: !ruby/object:Gem::Requirement
96
+ requirements:
97
+ - - ">="
98
+ - !ruby/object:Gem::Version
99
+ version: '0'
100
+ requirements: []
101
+ rubygems_version: 3.0.3
102
+ signing_key:
103
+ specification_version: 4
104
+ summary: Cursor based pagination for active_record currently
105
+ test_files: []