|
2 | 2 |
|
3 | 3 | module SmartListing |
4 | 4 | class Base |
5 | | - include Pagy::Backend |
| 5 | + include Pagy::Method |
6 | 6 |
|
7 | 7 | attr_reader :name, :collection, :options, :per_page, :sort, :page, :count, :params, :pagy_collection |
8 | 8 |
|
9 | 9 | # Params that should not be visible in pagination links (pages, per-page, sorting, etc.) |
10 | 10 | UNSAFE_PARAMS = %i[authenticity_token commit utf8 _method script_name].freeze |
11 | 11 |
|
12 | | - def initialize(name, collection, options = {}) |
| 12 | + def initialize(name, collection, view_context, options = {}) |
13 | 13 | @name = name |
| 14 | + @view_context = view_context |
14 | 15 | @pagy_collection = nil |
15 | 16 |
|
16 | 17 | config_profile = options.delete(:config_profile) |
@@ -53,7 +54,7 @@ def setup(params, cookies) |
53 | 54 | end |
54 | 55 |
|
55 | 56 | sort!(@options[:array]) |
56 | | - paginate!(@options[:array]) |
| 57 | + paginate! |
57 | 58 | end |
58 | 59 | # rubocop:enable Layout/LineLength |
59 | 60 |
|
@@ -117,6 +118,10 @@ def base_param |
117 | 118 | "#{name}_smart_listing" |
118 | 119 | end |
119 | 120 |
|
| 121 | + def request |
| 122 | + @view_context.request |
| 123 | + end |
| 124 | + |
120 | 125 | private |
121 | 126 |
|
122 | 127 | def get_param(key, store = @params) |
@@ -162,16 +167,20 @@ def sort!(is_array) |
162 | 167 | is_array ? sort_array : sort_active_record |
163 | 168 | end |
164 | 169 |
|
165 | | - def paginate!(is_array) |
| 170 | + def paginate! |
166 | 171 | return unless @options[:paginate] && @per_page > 0 |
167 | 172 |
|
168 | | - params = pagy_options.fetch(:params, {}).merge(smart_listing_name: name) |
| 173 | + root_key = :"#{name}_smart_listing" |
| 174 | + sort = @view_context.params.dig(root_key, :sort)&.to_unsafe_h |
| 175 | + params = pagy_options.fetch(:params, {}).merge(smart_listing_name: name) |
| 176 | + querify = ->(p) { merge_params(p, params, root_key, sort) } |
169 | 177 |
|
170 | | - if is_array |
171 | | - @pagy_collection, @collection = pagy_array(@collection, page: @page, limit: @per_page, params: params) |
172 | | - else |
173 | | - @pagy_collection, @collection = pagy(@collection, page: @page, limit: @per_page, params: params) |
174 | | - end |
| 178 | + @pagy_collection, @collection = pagy(:offset, @collection, page: @page, limit: @per_page, root_key: root_key, querify: querify) |
| 179 | + end |
| 180 | + |
| 181 | + def merge_params(pagy_params, params, root_key, sort) |
| 182 | + pagy_params[root_key][:sort] = sort if sort |
| 183 | + pagy_params.merge!(params) |
175 | 184 | end |
176 | 185 |
|
177 | 186 | def sort_array |
|
0 commit comments