active_record-cursor_paginator 0.1.0

Sign up to get free protection for your applications and to get access to all the features.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: 5f0bf9b4efedd42ab91e3ad4cc65ceddc323e14482d412e191cd5f999c4b7652
4
+ data.tar.gz: '05907e8c002d776c4f06a7dae8352e058eab6790eaf509af22ba612c287c7369'
5
+ SHA512:
6
+ metadata.gz: cbf06f52e6d3acb9be08eb0ec8e88a53d33000670783bb9841d5ece1a67b400478bee8ebbf3bf4a1f85c0f549b42834f5e760a740713a8b469833550495f0b2b
7
+ data.tar.gz: 1ff2dd7da5bd5ed0e5d63eeee7a41b4d80b0f3ab17dc511843859b63b1b624373ba64c4a84df745cca08bcd043d24ac90d0eb62a75cb55fa7c3151979ccf8426
data/.rspec ADDED
@@ -0,0 +1,3 @@
1
+ --format documentation
2
+ --color
3
+ --require spec_helper
data/.rubocop.yml ADDED
@@ -0,0 +1,489 @@
1
+ inherit_from: .rubocop_todo.yml
2
+ inherit_mode:
3
+ merge:
4
+ - Exclude
5
+
6
+ # ref)
7
+ # https://raw.githubusercontent.com/onk/onkcop/master/config/rubocop.yml
8
+
9
+ # 自動生成されるものはチェック対象から除外する
10
+ AllCops:
11
+ SuggestExtensions: false
12
+ NewCops: enable
13
+ Exclude:
14
+ - 'public/**/*'
15
+ - 'tmp/**/*'
16
+ - 'log/**/*'
17
+ - "vendor/**/*"
18
+ - "bin/*"
19
+ - "Gemfile*"
20
+ - "db/schema.rb"
21
+ - "db/seeds.rb"
22
+ - 'db/migrate/*_init_schema.rb' # squasher generated
23
+ - "frontend/**/*"
24
+ - 'spec/fixtures/**/*'
25
+ - 'terraform/**/*'
26
+ - "app/lib/qwan_exception.rb"
27
+ - "app/controllers/test_data_controller.rb"
28
+ - "app/apis/api/v1/concerns/errors.rb"
29
+ - 'docker/**/*'
30
+ - '**/node_modules/**/*'
31
+
32
+ #################### Layout ################################
33
+
34
+ # * 警告 120文字
35
+ # * 禁止 160文字
36
+ # のイメージ
37
+ Layout/LineLength:
38
+ Max: 160
39
+ Exclude:
40
+ - "db/migrate/*.rb"
41
+ - "app/lib/ngword.rb"
42
+ - "app/exceptions/qwan_exception/shop_remove_location_despite_has_ticket.rb"
43
+ - "spec/apis/api/v1/contact_spec.rb"
44
+ - "spec/ledger/report/tenant_transactions_spec.rb"
45
+ - "spec/ledger/report/transactions_spec.rb"
46
+
47
+ # ガード句と本質を分けるのは良いコードスタイルなので有効化
48
+ Layout/EmptyLineAfterGuardClause:
49
+ Enabled: true
50
+
51
+ # メソッドをグループ分けして書き順を揃えておくと読みやすくなる。
52
+ # 多少のツラミはあるかもしれない。
53
+ # TODO: https://github.com/pocke/rubocop-rails-order_model_declarative_methods
54
+ Layout/ClassStructure:
55
+ Enabled: true
56
+
57
+ # メソッドチェーンの改行は末尾に . を入れる
58
+ # * REPL に貼り付けた際の暴発を防ぐため
59
+ # * 途中にコメントをはさむことができて実用上圧倒的に便利
60
+ Layout/DotPosition:
61
+ EnforcedStyle: trailing
62
+
63
+ # 桁揃えが綺麗にならないことが多いので migration は除外
64
+ Layout/ExtraSpacing:
65
+ Exclude:
66
+ - "db/migrate/*.rb"
67
+
68
+ # special_inside_parentheses (default) と比べて
69
+ # * 横に長くなりづらい
70
+ # * メソッド名の長さが変わったときに diff が少ない
71
+ Layout/FirstArrayElementIndentation:
72
+ EnforcedStyle: special_inside_parentheses
73
+
74
+ # ({ と hash を開始した場合に ( の位置にインデントさせる
75
+ # そもそも {} が必要ない可能性が高いが Style/BracesAroundHashParameters はチェックしないことにしたので
76
+ Layout/FirstHashElementIndentation:
77
+ EnforcedStyle: special_inside_parentheses
78
+ # EnforcedStyle: align_braces
79
+
80
+ # private/protected は一段深くインデントする
81
+ Layout/IndentationConsistency:
82
+ EnforcedStyle: indented_internal_methods
83
+
84
+ # メソッドチェーン感がより感じられるインデントにする
85
+ Layout/MultilineMethodCallIndentation:
86
+ EnforcedStyle: indented_relative_to_receiver
87
+
88
+ # {} は 1 行で書くときに主に使われるので、スペースよりも
89
+ # 横に長くならない方が嬉しさが多い。
90
+ # そもそも {| のスタイルの方が一般的だったと認識している。
91
+ Layout/SpaceInsideBlockBraces:
92
+ SpaceBeforeBlockParameters: false
93
+
94
+ # その時々でやりたい表現を尊重すれば良いと思う
95
+ Layout/LineContinuationLeadingSpace:
96
+ Enabled: false
97
+
98
+ #################### Lint ##################################
99
+
100
+ # spec 内では
101
+ # expect { subject }.to change { foo }
102
+ # という書き方をよく行うので () を省略したい。
103
+ # { foo } は明らかに change に紐付く。
104
+ Lint/AmbiguousBlockAssociation:
105
+ Exclude:
106
+ - "spec/**/*_spec.rb"
107
+
108
+ # Style/EmptyCaseCondition と同じく網羅の表現力が empty when を認めた方が高いし、
109
+ # 頻出する対象を最初の when で撥ねるのはパフォーマンス向上で頻出する。
110
+ # また、
111
+ # case foo
112
+ # when 42
113
+ # # nop
114
+ # when 1..100
115
+ # ...
116
+ # end
117
+ # と、下の when がキャッチしてしまう場合等に対応していない。
118
+ # See. http://tech.sideci.com/entry/2016/11/01/105900
119
+ Lint/EmptyWhen:
120
+ Enabled: false
121
+
122
+ # RuntimeError は「特定の Error を定義できない場合」なので、
123
+ # 定義できるエラーは RuntimeError ではなく StandardError を継承する。
124
+ Lint/InheritException:
125
+ EnforcedStyle: standard_error
126
+
127
+ # * 同名のメソッドがある場合にローカル変数に `_` を付ける
128
+ # * 一時変数として `_` を付ける
129
+ # というテクニックは頻出する
130
+ Lint/UnderscorePrefixedVariableName:
131
+ Enabled: false
132
+
133
+ # 子クラスで実装させるつもりで中身が
134
+ # raise NotImplementedError
135
+ # のみのメソッドが引っかかるので。
136
+ # (raise せずに中身が空だと IgnoreEmptyMethods でセーフ)
137
+ Lint/UnusedMethodArgument:
138
+ Enabled: false
139
+
140
+ # select 以外では引っかからないと思うので
141
+ # mutating_methods のチェックを有効に。
142
+ # TODO: select は引数が無い (ブロックのみ) の場合にだけチェックする
143
+ # ようにすると誤検知がほぼ無くなる?
144
+ Lint/Void:
145
+ CheckForMethodsWithNoSideEffects: true
146
+
147
+ # messageを取り回してるだけなのでわざわざsuperを呼ばなくても良さそう
148
+ Lint/MissingSuper:
149
+ Exclude:
150
+ - 'app/exceptions/qwan_exception/*'
151
+
152
+ #################### Metrics ###############################
153
+
154
+ # 目標: 20 まで下げたい。
155
+ Metrics/AbcSize:
156
+ Max: 36
157
+ Exclude:
158
+ - "db/migrate/*"
159
+ - "app/controllers/test_data_controller.rb"
160
+ - "app/models/mission_master.rb"
161
+ - "app/models/region_player/status.rb"
162
+ - 'app/models/concerns/region_location_report_concern.rb'
163
+
164
+ # Gemfile, Guardfile は DSL 的で基本的に複雑にはならないので除外
165
+ # rake, rspec, environments, routes は巨大な block 不可避なので除外
166
+ # TODO: ExcludedMethods の精査
167
+ Metrics/BlockLength:
168
+ Max: 30
169
+ Exclude:
170
+ - "Rakefile"
171
+ - "**/*.rake"
172
+ - "spec/**/*.rb"
173
+ - "Gemfile"
174
+ - "Guardfile"
175
+ - "config/environments/*.rb"
176
+ - "config/routes.rb"
177
+ - "config/routes/**/*.rb"
178
+ - "*.gemspec"
179
+ - "app/apis/**/*.rb"
180
+ - 'app/models/concerns/firebase_auth_concern.rb'
181
+ - 'app/models/concerns/region_location_report_concern.rb'
182
+ - 'db/migrate/*_init_schema.rb' # squasher generated
183
+
184
+ # 6 は強すぎるので緩める
185
+ Metrics/CyclomaticComplexity:
186
+ Max: 11
187
+ Exclude:
188
+ - "app/models/mission_master.rb"
189
+
190
+ Metrics/ClassLength:
191
+ Max: 500
192
+ CountAsOne: ['array', 'hash', 'heredoc']
193
+ Exclude:
194
+ - 'db/migrate/*_init_schema.rb' # squasher generated
195
+
196
+ # 20 行超えるのは migration ファイル以外滅多に無い
197
+ Metrics/MethodLength:
198
+ Max: 30
199
+ Exclude:
200
+ - "db/migrate/*.rb"
201
+ - "app/models/**/search.rb"
202
+ - "app/controllers/test_data_controller.rb"
203
+ - "app/models/mission_master.rb"
204
+ - "app/models/region_player/status.rb"
205
+
206
+ # 分岐の数。ガード句を多用しているとデフォルト 7 だと厳しい
207
+ Metrics/PerceivedComplexity:
208
+ Max: 10
209
+ Exclude:
210
+ - "app/models/mission_master.rb"
211
+
212
+ Metrics/ParameterLists:
213
+ Max: 8
214
+
215
+ #################### Naming ################################
216
+
217
+ # 3 文字未満だと指摘されるが、未使用を示す _ や e(rror), b(lock),
218
+ # n(umber) といった 1 文字変数は頻出するし、前置詞(by, to, ...)や
219
+ # よく知られた省略語 (op: operator とか pk: primary key とか) も妥当。
220
+ # 変数 s にどんな文字列かを形容したい場合と、不要な場合とがある=無効
221
+ Naming/MethodParameterName:
222
+ Enabled: false
223
+
224
+ Naming/VariableNumber:
225
+ Enabled: false
226
+
227
+ Naming/InclusiveLanguage:
228
+ Enabled: true
229
+ FlaggedTerms:
230
+ blacklist:
231
+ Regex: '(?!)' # table名に使ってしまっているので修正は難しい
232
+
233
+ #################### Security ##############################
234
+
235
+ # 毎回 YAML.safe_load(yaml_str, [Date, Time]) するのは面倒で。。
236
+ Security/YAMLLoad:
237
+ Enabled: false
238
+
239
+ #################### Style #################################
240
+
241
+ # レキシカルスコープの扱いが alias_method の方が自然。
242
+ # https://ernie.io/2014/10/23/in-defense-of-alias/ のように
243
+ # 問題になる場合は自分で緩める。
244
+ Style/Alias:
245
+ EnforcedStyle: prefer_alias_method
246
+
247
+ # redirect_to xxx and return のイディオムを維持したい
248
+ Style/AndOr:
249
+ EnforcedStyle: conditionals
250
+
251
+ # 日本語のコメントを許可する
252
+ Style/AsciiComments:
253
+ Enabled: false
254
+
255
+ # Use a consistent style for named format string tokens.
256
+ Style/FormatStringToken:
257
+ Enabled: false
258
+
259
+ # do .. end から更にメソッドチェーンすると見づらいので
260
+ # auto-correct せず、自分で修正する
261
+ # spec 内は見た目が綺麗になるので許可
262
+ Style/BlockDelimiters:
263
+ AutoCorrect: false
264
+ Exclude:
265
+ - "spec/**/*_spec.rb"
266
+
267
+ # scope が違うとか親 module の存在確認が必要とかデメリットはあるが、
268
+ # namespace 付きのクラスはかなり頻繁に作るので簡単に書きたい。
269
+ Style/ClassAndModuleChildren:
270
+ Enabled: false
271
+
272
+ # Style/CollectionMethods 自体は無効になっているのだが、
273
+ # https://github.com/bbatsov/rubocop/issues/1084
274
+ # https://github.com/bbatsov/rubocop/issues/1334
275
+ # Performance/Detect がこの設定値を見るので PreferredMethods だけ変更しておく。
276
+ #
277
+ # デフォルト値から変えたのは
278
+ # find -> detect
279
+ # ActiveRecord の find と間違えやすいため
280
+ # reduce -> inject
281
+ # detect, reject, select と並べたときに韻を踏んでいるため。
282
+ # collect -> map を維持しているのは文字数が圧倒的に少ないため。
283
+ Style/CollectionMethods:
284
+ PreferredMethods:
285
+ detect: "detect"
286
+ find: "detect"
287
+ inject: "inject"
288
+ reduce: "inject"
289
+
290
+ # ドキュメントの無い public class を許可する
291
+ Style/Documentation:
292
+ Enabled: false
293
+
294
+ # !! のイディオムは積極的に使う
295
+ Style/DoubleNegation:
296
+ Enabled: false
297
+
298
+ # case
299
+ # when ios?
300
+ # when android?
301
+ # end
302
+ # のようなものは case の方が網羅の表現力が高い
303
+ Style/EmptyCaseCondition:
304
+ Enabled: false
305
+
306
+ # 明示的に else で nil を返すのは分かりやすいので許可する
307
+ Style/EmptyElse:
308
+ EnforcedStyle: empty
309
+
310
+ # 空メソッドの場合だけ1行で書かなければいけない理由が無い
311
+ # 「セミコロンは使わない」に寄せた方がルールがシンプル
312
+ Style/EmptyMethod:
313
+ EnforcedStyle: expanded
314
+
315
+ # いずれかに揃えるのならば `sprintf` や `format` より String#% が好きです
316
+ Style/FormatString:
317
+ EnforcedStyle: percent
318
+
319
+ # まだ対応するには早い
320
+ Style/FrozenStringLiteralComment:
321
+ Enabled: false
322
+
323
+ # if 文の中に 3 行程度のブロックを書くぐらいは許容した方が現実的
324
+ # NOTE: https://github.com/bbatsov/rubocop/commit/29945958034db13af9e8ff385ec58cb9eb464596
325
+ # の影響で、if 文の中身が 1 行の場合に警告されるようになっている。
326
+ # Style/IfUnlessModifier の設定見てくれないかなぁ? (v0.36.0)
327
+ Style/GuardClause:
328
+ MinBodyLength: 5
329
+
330
+ # rake タスクの順序の hash は rocket を許可する
331
+ Style/HashSyntax:
332
+ EnforcedShorthandSyntax: either
333
+ Exclude:
334
+ - "**/*.rake"
335
+ - "Rakefile"
336
+
337
+ # 平たくしてしまうと条件のグルーピングが脳内モデルとズレやすい
338
+ Style/IfInsideElse:
339
+ Enabled: false
340
+
341
+ # 条件式の方を意識させたい場合には後置の if/unless を使わない方が分かりやすい
342
+ Style/IfUnlessModifier:
343
+ Enabled: false
344
+
345
+ # scope 等は複数行でも lambda ではなく ->{} で揃えた方が見た目が綺麗
346
+ Style/Lambda:
347
+ EnforcedStyle: literal
348
+
349
+ # end.some_method とチェインするのはダサい
350
+ # Style/BlockDelimiters と相性が悪いけど、頑張ってコードを修正してください
351
+ Style/MethodCalledOnDoEndBlock:
352
+ Enabled: true
353
+
354
+ # この 2 つは単発で動かすのが分かっているので Object を汚染しても問題ない。
355
+ # spec/dummy は Rails Engine を開発するときに絶対に引っかかるので入れておく。
356
+ Style/MixinUsage:
357
+ Exclude:
358
+ - "bin/setup"
359
+ - "bin/update"
360
+ - "spec/dummy/bin/setup"
361
+ - "spec/dummy/bin/update"
362
+
363
+ # 1_000_000 と区切り文字が 2 個以上必要になる場合のみ _ 区切りを必須にする
364
+ # 10_000_00 は許可しない。(これは例えば 10000 ドルをセント単位にする時に便利だが
365
+ # 頻出しないので foolproof に振る
366
+ Style/NumericLiterals:
367
+ MinDigits: 7
368
+ Strict: true
369
+
370
+ # foo.positive? は foo > 0 に比べて意味が曖昧になる
371
+ # foo.zero? は許可したいけどメソッドごとに指定できないので一括で disable に
372
+ Style/NumericPredicate:
373
+ Enabled: false
374
+
375
+ # falsy な場合という条件式の方を意識させたい場合がある。
376
+ # Style/IfUnlessModifier と同じ雰囲気。
377
+ Style/OrAssignment:
378
+ Enabled: false
379
+
380
+ # 正規表現にマッチさせた時の特殊変数の置き換えは Regex.last_match ではなく
381
+ # 名前付きキャプチャを使って参照したいので auto-correct しない
382
+ Style/PerlBackrefs:
383
+ AutoCorrect: false
384
+
385
+ # Hash#has_key? の方が key? よりも意味が通る
386
+ Style/PreferredHashMethods:
387
+ EnforcedStyle: verbose
388
+
389
+ # begin - end を省略しろというのは分かりにくくなるため省略を推奨しない
390
+ Style/RedundantBegin:
391
+ Enabled: false
392
+
393
+ # 受け取り側で multiple assignment しろというのを明示
394
+ Style/RedundantReturn:
395
+ AllowMultipleReturnValues: true
396
+
397
+ # 特に model 内において、ローカル変数とメソッド呼び出しの区別をつけた方が分かりやすい場合が多い
398
+ Style/RedundantSelf:
399
+ Enabled: false
400
+
401
+ # 無指定だと StandardError を rescue するのは常識の範疇なので。
402
+ Style/RescueStandardError:
403
+ EnforcedStyle: implicit
404
+
405
+ # user&.admin? が、[nil, true, false] の 3 値を返すことに一瞬で気づけず
406
+ # boolean を返すっぽく見えてしまうので無効に。
407
+ # user && user.admin? なら短絡評価で nil が返ってくるのが一目で分かるので。
408
+ # (boolean を返すメソッド以外なら積極的に使いたいんだけどねぇ
409
+ #
410
+ # 他に auto-correct してはいけないパターンとして
411
+ # if hoge && hoge.count > 1
412
+ # がある。
413
+ Style/SafeNavigation:
414
+ Enabled: false
415
+
416
+ # spec 内は見た目が綺麗になるので許可
417
+ Style/Semicolon:
418
+ Exclude:
419
+ - "spec/**/*_spec.rb"
420
+
421
+ # * 式展開したい場合に書き換えるのが面倒
422
+ # * 文章ではダブルクォートよりもシングルクォートの方が頻出する
423
+ # ことから EnforcedStyle: double_quotes 推奨
424
+ Style/StringLiterals:
425
+ EnforcedStyle: single_quotes
426
+
427
+ # 式展開中でもダブルクォートを使う
428
+ # 普段の文字列リテラルがダブルクォートなので使い分けるのが面倒
429
+ Style/StringLiteralsInInterpolation:
430
+ EnforcedStyle: double_quotes
431
+
432
+ # String#intern は ruby の内部表現すぎるので String#to_sym を使う
433
+ Style/StringMethods:
434
+ Enabled: true
435
+
436
+ # %w() と %i() が見分けづらいので Style/WordArray と合わせて無効に。
437
+ # 書き手に委ねるという意味で、Enabled: false にしています。使っても良い。
438
+ Style/SymbolArray:
439
+ Enabled: false
440
+
441
+ # 三項演算子は分かりやすく使いたい。
442
+ # () を外さない方が条件式が何なのか読み取りやすいと感じる。
443
+ Style/TernaryParentheses:
444
+ EnforcedStyle: require_parentheses_when_complex
445
+
446
+ # 複数行の場合はケツカンマを入れる(引数)
447
+ # Ruby は関数の引数もカンマを許容しているので
448
+ # * 単行は常にケツカンマ無し
449
+ # * 複数行は常にケツカンマ有り
450
+ # に統一したい。
451
+ # 見た目がアレだが、ES2017 でも関数引数のケツカンマが許容されるので
452
+ # 世界はそちらに向かっている。
453
+ Style/TrailingCommaInArguments:
454
+ EnforcedStyleForMultiline: comma
455
+
456
+ # 複数行の場合はケツカンマを入れる(Arrayリテラル)
457
+ # JSON がケツカンマを許していないという反対意見もあるが、
458
+ # 古い JScript の仕様に縛られる必要は無い。
459
+ # IE9 以降はリテラルでケツカンマ OK なので正しい差分行の検出に寄せる。
460
+ # 2 insertions(+), 1 deletion(-) ではなく、1 insertions
461
+ Style/TrailingCommaInArrayLiteral:
462
+ EnforcedStyleForMultiline: comma
463
+
464
+ # 複数行の場合はケツカンマを入れる(Hashリテラル)
465
+ Style/TrailingCommaInHashLiteral:
466
+ EnforcedStyleForMultiline: comma
467
+
468
+ # %w() と %i() が見分けづらいので Style/SymbolArray と合わせて無効に。
469
+ # 書き手に委ねるという意味で、Enabled: false にしています。使っても良い。
470
+ Style/WordArray:
471
+ Enabled: false
472
+
473
+ # 0 <= foo && foo < 5 のように数直線上に並べるのは
474
+ # コードを読みやすくするテクニックなので forbid_for_equality_operators_only に。
475
+ Style/YodaCondition:
476
+ EnforcedStyle: forbid_for_equality_operators_only
477
+
478
+ # 条件式で arr.size > 0 が使われた時に
479
+ # if !arr.empty?
480
+ # else
481
+ # end
482
+ # に修正されるのが嫌。
483
+ # 中身を入れ替えて否定外しても良いんだけど、どちらが例外的な処理なのかが分かりづらくなる。
484
+ Style/ZeroLengthPredicate:
485
+ Enabled: false
486
+
487
+ # =begin...=end によるブロックコメントを許可する
488
+ Style/BlockComments:
489
+ Enabled: false
data/.rubocop_todo.yml ADDED
@@ -0,0 +1,7 @@
1
+ # This configuration was generated by
2
+ # `rubocop --auto-gen-config --auto-gen-only-exclude --exclude-limit 999999`
3
+ # on 2023-09-20 08:02:13 UTC using RuboCop version 1.56.3.
4
+ # The point is for the user to remove these configuration records
5
+ # one by one as the offenses are removed from the code base.
6
+ # Note that changes in the inspected code, or installation of new
7
+ # versions of RuboCop, may require this file to be generated again.
@@ -0,0 +1,84 @@
1
+ # Contributor Covenant Code of Conduct
2
+
3
+ ## Our Pledge
4
+
5
+ We as members, contributors, and leaders pledge to make participation in our community a harassment-free experience for everyone, regardless of age, body size, visible or invisible disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, religion, or sexual identity and orientation.
6
+
7
+ We pledge to act and interact in ways that contribute to an open, welcoming, diverse, inclusive, and healthy community.
8
+
9
+ ## Our Standards
10
+
11
+ Examples of behavior that contributes to a positive environment for our community include:
12
+
13
+ * Demonstrating empathy and kindness toward other people
14
+ * Being respectful of differing opinions, viewpoints, and experiences
15
+ * Giving and gracefully accepting constructive feedback
16
+ * Accepting responsibility and apologizing to those affected by our mistakes, and learning from the experience
17
+ * Focusing on what is best not just for us as individuals, but for the overall community
18
+
19
+ Examples of unacceptable behavior include:
20
+
21
+ * The use of sexualized language or imagery, and sexual attention or
22
+ advances of any kind
23
+ * Trolling, insulting or derogatory comments, and personal or political attacks
24
+ * Public or private harassment
25
+ * Publishing others' private information, such as a physical or email
26
+ address, without their explicit permission
27
+ * Other conduct which could reasonably be considered inappropriate in a
28
+ professional setting
29
+
30
+ ## Enforcement Responsibilities
31
+
32
+ Community leaders are responsible for clarifying and enforcing our standards of acceptable behavior and will take appropriate and fair corrective action in response to any behavior that they deem inappropriate, threatening, offensive, or harmful.
33
+
34
+ Community leaders have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, and will communicate reasons for moderation decisions when appropriate.
35
+
36
+ ## Scope
37
+
38
+ This Code of Conduct applies within all community spaces, and also applies when an individual is officially representing the community in public spaces. Examples of representing our community include using an official e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event.
39
+
40
+ ## Enforcement
41
+
42
+ Instances of abusive, harassing, or otherwise unacceptable behavior may be reported to the community leaders responsible for enforcement at sugiyama-shinichi@kayac.com. All complaints will be reviewed and investigated promptly and fairly.
43
+
44
+ All community leaders are obligated to respect the privacy and security of the reporter of any incident.
45
+
46
+ ## Enforcement Guidelines
47
+
48
+ Community leaders will follow these Community Impact Guidelines in determining the consequences for any action they deem in violation of this Code of Conduct:
49
+
50
+ ### 1. Correction
51
+
52
+ **Community Impact**: Use of inappropriate language or other behavior deemed unprofessional or unwelcome in the community.
53
+
54
+ **Consequence**: A private, written warning from community leaders, providing clarity around the nature of the violation and an explanation of why the behavior was inappropriate. A public apology may be requested.
55
+
56
+ ### 2. Warning
57
+
58
+ **Community Impact**: A violation through a single incident or series of actions.
59
+
60
+ **Consequence**: A warning with consequences for continued behavior. No interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, for a specified period of time. This includes avoiding interactions in community spaces as well as external channels like social media. Violating these terms may lead to a temporary or permanent ban.
61
+
62
+ ### 3. Temporary Ban
63
+
64
+ **Community Impact**: A serious violation of community standards, including sustained inappropriate behavior.
65
+
66
+ **Consequence**: A temporary ban from any sort of interaction or public communication with the community for a specified period of time. No public or private interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, is allowed during this period. Violating these terms may lead to a permanent ban.
67
+
68
+ ### 4. Permanent Ban
69
+
70
+ **Community Impact**: Demonstrating a pattern of violation of community standards, including sustained inappropriate behavior, harassment of an individual, or aggression toward or disparagement of classes of individuals.
71
+
72
+ **Consequence**: A permanent ban from any sort of public interaction within the community.
73
+
74
+ ## Attribution
75
+
76
+ This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 2.0,
77
+ available at https://www.contributor-covenant.org/version/2/0/code_of_conduct.html.
78
+
79
+ Community Impact Guidelines were inspired by [Mozilla's code of conduct enforcement ladder](https://github.com/mozilla/diversity).
80
+
81
+ [homepage]: https://www.contributor-covenant.org
82
+
83
+ For answers to common questions about this code of conduct, see the FAQ at
84
+ https://www.contributor-covenant.org/faq. Translations are available at https://www.contributor-covenant.org/translations.
data/Gemfile ADDED
@@ -0,0 +1,18 @@
1
+ # frozen_string_literal: true
2
+
3
+ source "https://rubygems.org"
4
+
5
+ # Specify your gem's dependencies in active_record-cursor_pagination.gemspec
6
+ gemspec
7
+
8
+ gem "rake", "~> 13.0"
9
+
10
+ gem "rspec", "~> 3.0"
11
+
12
+ gem "rubocop", "~> 1.21"
13
+
14
+ group :test do
15
+ gem 'temping'
16
+ gem 'pg', '>= 1.2', '< 2.0'
17
+ gem 'mysql2', '~> 0.5'
18
+ end
data/Gemfile.lock ADDED
@@ -0,0 +1,88 @@
1
+ PATH
2
+ remote: .
3
+ specs:
4
+ active_record-cursor_paginator (0.1.0)
5
+ activerecord (>= 6.0)
6
+
7
+ GEM
8
+ remote: https://rubygems.org/
9
+ specs:
10
+ activemodel (7.0.8)
11
+ activesupport (= 7.0.8)
12
+ activerecord (7.0.8)
13
+ activemodel (= 7.0.8)
14
+ activesupport (= 7.0.8)
15
+ activesupport (7.0.8)
16
+ concurrent-ruby (~> 1.0, >= 1.0.2)
17
+ i18n (>= 1.6, < 2)
18
+ minitest (>= 5.1)
19
+ tzinfo (~> 2.0)
20
+ ast (2.4.2)
21
+ base64 (0.1.1)
22
+ concurrent-ruby (1.2.2)
23
+ diff-lcs (1.5.0)
24
+ i18n (1.14.1)
25
+ concurrent-ruby (~> 1.0)
26
+ json (2.6.3)
27
+ language_server-protocol (3.17.0.3)
28
+ minitest (5.20.0)
29
+ mysql2 (0.5.5)
30
+ parallel (1.23.0)
31
+ parser (3.2.2.3)
32
+ ast (~> 2.4.1)
33
+ racc
34
+ pg (1.5.4)
35
+ racc (1.7.1)
36
+ rainbow (3.1.1)
37
+ rake (13.0.6)
38
+ regexp_parser (2.8.1)
39
+ rexml (3.2.6)
40
+ rspec (3.12.0)
41
+ rspec-core (~> 3.12.0)
42
+ rspec-expectations (~> 3.12.0)
43
+ rspec-mocks (~> 3.12.0)
44
+ rspec-core (3.12.2)
45
+ rspec-support (~> 3.12.0)
46
+ rspec-expectations (3.12.3)
47
+ diff-lcs (>= 1.2.0, < 2.0)
48
+ rspec-support (~> 3.12.0)
49
+ rspec-mocks (3.12.6)
50
+ diff-lcs (>= 1.2.0, < 2.0)
51
+ rspec-support (~> 3.12.0)
52
+ rspec-support (3.12.1)
53
+ rubocop (1.56.3)
54
+ base64 (~> 0.1.1)
55
+ json (~> 2.3)
56
+ language_server-protocol (>= 3.17.0)
57
+ parallel (~> 1.10)
58
+ parser (>= 3.2.2.3)
59
+ rainbow (>= 2.2.2, < 4.0)
60
+ regexp_parser (>= 1.8, < 3.0)
61
+ rexml (>= 3.2.5, < 4.0)
62
+ rubocop-ast (>= 1.28.1, < 2.0)
63
+ ruby-progressbar (~> 1.7)
64
+ unicode-display_width (>= 2.4.0, < 3.0)
65
+ rubocop-ast (1.29.0)
66
+ parser (>= 3.2.1.0)
67
+ ruby-progressbar (1.13.0)
68
+ temping (4.0.0)
69
+ activerecord (>= 5.2, < 7.1)
70
+ activesupport (>= 5.2, < 7.1)
71
+ tzinfo (2.0.6)
72
+ concurrent-ruby (~> 1.0)
73
+ unicode-display_width (2.4.2)
74
+
75
+ PLATFORMS
76
+ arm64-darwin-22
77
+
78
+ DEPENDENCIES
79
+ active_record-cursor_paginator!
80
+ mysql2 (~> 0.5)
81
+ pg (>= 1.2, < 2.0)
82
+ rake (~> 13.0)
83
+ rspec (~> 3.0)
84
+ rubocop (~> 1.21)
85
+ temping
86
+
87
+ BUNDLED WITH
88
+ 2.4.10
data/README.md ADDED
@@ -0,0 +1,62 @@
1
+ # Activerecord::CursorPaginator
2
+
3
+ This library is an implementation of cursor pagination for ActiveRecord relations based on "https://github.com/xing/rails_cursor_pagination.
4
+
5
+ Additional features are:
6
+ - receives a relation with orders, and it is unnecessary to specify orders toA this library separately
7
+ - supports bidirectional pagination.
8
+
9
+ ## Supported environment
10
+
11
+ - ActiveRecord
12
+ - mysql or Postgresql
13
+
14
+ ## Installation
15
+
16
+ Add the fllowing line to your `Gemfile` and execute `bundle install`
17
+
18
+ ```
19
+ gem 'active_record-cursor_paginator', git: 'https://github.com/ssugiyama/active_record-cursor_paginator'
20
+ ```
21
+
22
+ ## Usage
23
+
24
+ ```ruby
25
+ relation = Post.order(...)
26
+ page = ActiveRecord::CursorPaginator.new(relarion, direction: :forward, cursor: '...', per_page: 10)
27
+ ```
28
+
29
+ ### parameters of CursorPaginator
30
+ - cursor: String - cursor to paginate
31
+ - per_page: Integer - record count per page (default to 10)
32
+ - direction: Symbol - direction to paginate. `:forward` (default) or `:backward`
33
+
34
+ ### response of CursorPaginator
35
+
36
+ - `page.records`: Array - records splitted per page (Notice: not ActiveRecord::Relation but Array)
37
+ - `page.start_cursor`: String - cursor of the first record. used for the backward paginate call.
38
+ - `page.end_cursor`: String - cursor of the last record. used for the forward paginate call.
39
+ - `page.total`: Integer - total count of relation
40
+ - `page.next_page?`: Boolean - whether having the next page forward or not
41
+ - `page.previous_page?`: Boolean - whether having the next page backward or not
42
+
43
+ ## Development
44
+
45
+ ### Run test
46
+
47
+ ```shell
48
+ ADAPTER=mysql bundle exec rspec
49
+ ADAPTER=postgresql bundle exec rspec
50
+ ```
51
+
52
+ ## Contributing
53
+
54
+ Bug reports and pull requests are welcome on GitHub at https://github.com/ssugiyama/activerecord-cursor_paginator. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the [code of conduct](https://github.com/ssugiyama/activerecord-cursor_paginator/blob/main/CODE_OF_CONDUCT.md).
55
+
56
+ ## License
57
+
58
+ The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
59
+
60
+ ## Code of Conduct
61
+
62
+ Everyone interacting in the Activerecord::CursorPagination project's codebases, issue trackers, chat rooms and mailing lists is expected to follow the [code of conduct](https://github.com/ssugiyama/activerecord-cursor_paginator/blob/main/CODE_OF_CONDUCT.md).
data/Rakefile ADDED
@@ -0,0 +1,12 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'bundler/gem_tasks'
4
+ require 'rspec/core/rake_task'
5
+
6
+ RSpec::Core::RakeTask.new(:spec)
7
+
8
+ require 'rubocop/rake_task'
9
+
10
+ RuboCop::RakeTask.new
11
+
12
+ task default: %i[spec rubocop]
@@ -0,0 +1,7 @@
1
+ # frozen_string_literal: true
2
+
3
+ module ActiveRecord
4
+ class CursorPaginator
5
+ VERSION = '0.1.0'
6
+ end
7
+ end
@@ -0,0 +1,261 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'active_record'
4
+ require_relative 'cursor_paginator/version'
5
+
6
+ module ActiveRecord
7
+ class CursorPaginator
8
+ DIRECTIONS = [
9
+ DIRECTION_FORWARD = :forward,
10
+ DIRECTION_BACKWARD = :backward,
11
+ ].freeze
12
+
13
+ class ParameterError < StandardError; end
14
+ class InvalidCursorError < ParameterError; end
15
+ class InvalidOrderError < ParameterError; end
16
+
17
+ # @param relation [ActiveRecord::Relation]
18
+ # Relation that will be paginated.
19
+ # @param per_page [Integer, nil]
20
+ # Number of records to return.
21
+ # @param cursor [String, nil]
22
+ # Cursor to paginate
23
+ # @param order [Array, Hash, Symbol, nil]
24
+ # Column to order by. If none is provided, will default to ID column.
25
+ def initialize(relation, per_page: nil, cursor: nil, direction: DIRECTION_FORWARD)
26
+ @is_forward_pagination = direction == DIRECTION_FORWARD
27
+ relation = relation.order(:id) if relation.order_values.empty?
28
+ relation = relation.reverse_order unless @is_forward_pagination
29
+ @fields = extract_order_fields(relation)
30
+ @fields.push({ 'id' => :asc }) if @fields.last.keys.first != 'id'
31
+ @relation = relation.reorder(@fields)
32
+ @cursor = cursor
33
+ @page_size = per_page
34
+
35
+ @memos = {}
36
+ end
37
+
38
+ # extract order parameter from relation as the format : [ { field1 => :asc}, { field2 => :desc}, ...]
39
+ # @param relation [ActiveRecord::Relation]
40
+ # @return [Array]
41
+ def extract_order_fields(relation)
42
+ orders = relation.order_values
43
+ fields = orders.flat_map do |o|
44
+ case o
45
+ when Arel::Attribute # .order(arel_table[:id])
46
+ { o.name => :asc }
47
+ when Arel::Nodes::Ascending # .order(id: :asc), .order(:id)
48
+ { o.expr.name => :asc }
49
+ when Arel::Nodes::Descending # .order(id: :desc)
50
+ { o.expr.name => :desc }
51
+ when String # .order('id desc')
52
+ o.split(',').map! do |s|
53
+ s.strip!
54
+ matches = s.match(/\A(\w+)(?:\s+(asc|desc))?\Z/i)
55
+ raise InvalidOrderError, 'relation has an unsupported order.' if matches.nil? || matches.length < 3
56
+
57
+ { matches[1] => (matches[2] || 'asc').downcase.to_sym }
58
+ end
59
+ else # complex arel expression
60
+ raise InvalidOrderError, 'relation has an unsupported order.'
61
+ end
62
+ end
63
+ fields.flatten
64
+ end
65
+
66
+ # Cursor of the first record on the current page
67
+ #
68
+ # @return [String, nil]
69
+ def start_cursor
70
+ return if records.empty?
71
+
72
+ cursor_for_record(records.first)
73
+ end
74
+
75
+ # Cursor of the last record on the current page
76
+ #
77
+ # @return [String, nil]
78
+ def end_cursor
79
+ return if records.empty?
80
+
81
+ cursor_for_record(records.last)
82
+ end
83
+
84
+ # Get the total number of records in the given relation
85
+ #
86
+ # @return [Integer]
87
+ def total
88
+ memoize(:total) { @relation.reorder('').size }
89
+ end
90
+
91
+ # Check if there is a page before the current one.
92
+ #
93
+ # @return [TrueClass, FalseClass]
94
+ def previous_page?
95
+ if paginate_forward?
96
+ # When paginating forwards and cursor is specified,
97
+ # we have the previous page, because specified cursor may be the end cursor of a page
98
+ @cursor.present?
99
+ else
100
+ # When paginating backwards, if we managed to load one more record than
101
+ # requested, this record will be available on the previous page.
102
+ records_plus_one.size > @page_size
103
+ end
104
+ end
105
+
106
+ # Check if there is another page after the current one.
107
+ #
108
+ # @return [TrueClass, FalseClass]
109
+ def next_page?
110
+ if paginate_forward?
111
+ # When paginating forward, if we managed to load one more record than
112
+ # requested, this record will be available on the next page.
113
+ records_plus_one.size > @page_size
114
+ else
115
+ # When paginating backward, in most cases,
116
+ # we have the next page, because specified cursor may be the start cursor of a page
117
+ true
118
+ end
119
+ end
120
+
121
+ # Load the correct records and return them in the right order
122
+ #
123
+ # @return [Array<ActiveRecord>]
124
+ def records
125
+ records = records_plus_one.first(@page_size)
126
+ paginate_forward? ? records : records.reverse
127
+ end
128
+
129
+ # Check if the pagination direction is forward
130
+ #
131
+ # @return [TrueClass, FalseClass]
132
+ def paginate_forward?
133
+ @is_forward_pagination
134
+ end
135
+
136
+ private
137
+
138
+ # Apply limit to filtered and sorted relation that contains one item more
139
+ # than the user-requested page size. This is useful for determining if there
140
+ # is an additional page available without having to do a separate DB query.
141
+ # Then, fetch the records from the database to prevent multiple queries to
142
+ # load the records and count them.
143
+ #
144
+ # @return [ActiveRecord::Relation]
145
+ def records_plus_one
146
+ memoize :records_plus_one do
147
+ filtered_and_sorted_relation.first(@page_size + 1)
148
+ end
149
+ end
150
+
151
+ # Generate a cursor for the given record and ordering field. The cursor
152
+ # encodes all the data required to then paginate based on it with the given
153
+ # ordering field.
154
+ #
155
+ # If we only order by ID, the cursor doesn't need to include any other data.
156
+ # But if we order by any other field, the cursor needs to include both the
157
+ # value from this other field as well as the records ID to resolve the order
158
+ # of duplicates in the non-ID field.
159
+ #
160
+ # @param record [ActiveRecord] Model instance for which we want the cursor
161
+ # @return [String]
162
+ def cursor_for_record(record)
163
+ unencoded_cursor = @fields.map {|field| { field.keys.first => record[field.keys.first] } }
164
+ Base64.strict_encode64(unencoded_cursor.to_json)
165
+ end
166
+
167
+ # Decode the provided cursor. Either just returns the cursor's ID or in case
168
+ # of pagination on any other field, returns a tuple of first the cursor
169
+ # record's other field's value followed by its ID.
170
+ #
171
+ # @return [Integer, Array]
172
+ def decoded_cursor
173
+ memoize(:decoded_cursor) { JSON.parse(Base64.strict_decode64(@cursor)) }
174
+ rescue ArgumentError, JSON::ParserError
175
+ raise InvalidCursorError, 'The given cursor could not be decoded'
176
+ end
177
+
178
+ # Ensure that the relation has the ID column and any potential `order_by`
179
+ # column selected. These are required to generate the record's cursor and
180
+ # therefore it's crucial that they are part of the selected fields.
181
+ #
182
+ # @return [ActiveRecord::Relation]
183
+ def relation_with_cursor_fields
184
+ return @relation if @relation.select_values.blank?
185
+
186
+ relation = @relation
187
+
188
+ @fields.each do |field|
189
+ field = field.keys.first
190
+ relation = relation.select(field) unless @relation.select_values.include?(field)
191
+ end
192
+
193
+ relation
194
+ end
195
+
196
+ # The given relation with the right ordering applied. Takes custom order
197
+ # columns as well as custom direction and pagination into account.
198
+ #
199
+ # @return [ActiveRecord::Relation]
200
+ def sorted_relation
201
+ relation_with_cursor_fields
202
+ end
203
+
204
+ # Applies the filtering based on the provided cursor and order column to the
205
+ # sorted relation.
206
+ #
207
+ # @return [ActiveRecord::Relation]
208
+ def filtered_and_sorted_relation
209
+ memoize :filtered_and_sorted_relation do
210
+ next sorted_relation if @cursor.blank?
211
+
212
+ cursor = decoded_cursor
213
+ unless cursor.length == @fields.length && cursor.map {|field| field.keys.first } == @fields.map {|field| field.keys.first }
214
+ raise InvalidCursorError, 'The given cursor is mismatched with current query'
215
+ end
216
+
217
+ prev_fields = []
218
+ relation = nil
219
+ cursor.zip(@fields).each do |cursor_field, field|
220
+ direction = field.values.first
221
+ # range では 〜より大きいということが表現できないのでarel_tableを使う
222
+ op = (direction == :asc) ? :gt : :lt
223
+ current_field = [field.keys.first, cursor_field.values.first]
224
+ new_relation = build_filter_query(sorted_relation, op, current_field, prev_fields)
225
+ relation = relation.nil? ? new_relation : relation.or(new_relation)
226
+
227
+ prev_fields.push(current_field)
228
+ end
229
+ relation
230
+ end
231
+ end
232
+
233
+ # Ensures that given block is only executed exactly once and on subsequent
234
+ # calls returns result from first execution. Useful for memoizing methods.
235
+ #
236
+ # @param key [Symbol]
237
+ # Name or unique identifier of the method that is being memoized
238
+ # @yieldreturn [Object]
239
+ # @return [Object] Whatever the block returns
240
+ def memoize(key)
241
+ return @memos[key] if @memos.has_key?(key)
242
+
243
+ @memos[key] = yield
244
+ end
245
+
246
+ # Modelを[{ col1: :asc}, { col2: :asc}, { col3: :asc}] でソートする場合以下のようにする
247
+ # Model.where('col1 > ?').
248
+ # or(Model.where('col1 = ?').where('col2 > ?')).
249
+ # or(Model.where('col1 = ?').where('col2 = ?')).where('col3 > ?))
250
+ #
251
+ # @return [ActiveRecord::Relation]
252
+ def build_filter_query(sorted_relation, op, current_field, prev_fields)
253
+ relation = sorted_relation
254
+ prev_fields.each do |col, val|
255
+ relation = relation.where(relation.arel_table[col].send(:eq, val))
256
+ end
257
+ col, val = current_field
258
+ relation.where(relation.arel_table[col].send(op, val))
259
+ end
260
+ end
261
+ end
metadata ADDED
@@ -0,0 +1,74 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: active_record-cursor_paginator
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - Shinichi Sugiyama
8
+ autorequire:
9
+ bindir: exe
10
+ cert_chain: []
11
+ date: 2023-09-20 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: activerecord
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - ">="
18
+ - !ruby/object:Gem::Version
19
+ version: '6.0'
20
+ type: :runtime
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - ">="
25
+ - !ruby/object:Gem::Version
26
+ version: '6.0'
27
+ description: 'This library is an implementation of cursor pagination for ActiveRecord
28
+ relations based on "https://github.com/xing/rails_cursor_pagination". Additional
29
+ features are: - receives a relation with orders, and it is unnecessary to specify
30
+ orders to this library separately.- supports bidirectional pagination.'
31
+ email:
32
+ - sugiyama-shinichi@kayac.com
33
+ executables: []
34
+ extensions: []
35
+ extra_rdoc_files: []
36
+ files:
37
+ - ".rspec"
38
+ - ".rubocop.yml"
39
+ - ".rubocop_todo.yml"
40
+ - CODE_OF_CONDUCT.md
41
+ - Gemfile
42
+ - Gemfile.lock
43
+ - README.md
44
+ - Rakefile
45
+ - lib/active_record/cursor_paginator.rb
46
+ - lib/active_record/cursor_paginator/version.rb
47
+ homepage: https://github.com/ssugiyama/active_record-cursor_paginator
48
+ licenses:
49
+ - MIT
50
+ metadata:
51
+ homepage_uri: https://github.com/ssugiyama/active_record-cursor_paginator
52
+ source_code_uri: https://github.com/ssugiyama/active_record-cursor_paginator
53
+ changelog_uri: https://github.com/ssugiyama/active_record-cursor_paginator/Changelog.md
54
+ rubygems_mfa_required: 'true'
55
+ post_install_message:
56
+ rdoc_options: []
57
+ require_paths:
58
+ - lib
59
+ required_ruby_version: !ruby/object:Gem::Requirement
60
+ requirements:
61
+ - - ">="
62
+ - !ruby/object:Gem::Version
63
+ version: 2.7.0
64
+ required_rubygems_version: !ruby/object:Gem::Requirement
65
+ requirements:
66
+ - - ">="
67
+ - !ruby/object:Gem::Version
68
+ version: '0'
69
+ requirements: []
70
+ rubygems_version: 3.4.10
71
+ signing_key:
72
+ specification_version: 4
73
+ summary: cursor pagination for ActiveRecord
74
+ test_files: []