ransack_memory 0.1.0 → 1.0.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.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
- SHA1:
3
- metadata.gz: ee63c846270102691c62cd2a7af77912d7aa7651
4
- data.tar.gz: 8dd719ca19c83f10078157448a329f56ed959d9b
2
+ SHA256:
3
+ metadata.gz: 252f1335ff68549529db42ec9cf95206e952a56323bf310b557ca23573787af5
4
+ data.tar.gz: 6c68feb8c2f404efd9ceca918a56061f441c92b540318b8db017a6b18c38196c
5
5
  SHA512:
6
- metadata.gz: 444c11b00620bd325023254a05b48ea80bd53dd527164c0a6db96dc880bbf9098e0049fc49e7ab68ea3e98369febb53db37571e00497a8ba9e7df14b6f789c90
7
- data.tar.gz: fdd5cebf99c78325ad1f0744fd41ffbdf03f5a4d617dd0434e767e969cc2b84ebca9326ce1dd3e5024400c3b383e49e3c988e7a7538a07dead13344bc84534ab
6
+ metadata.gz: c42fa56161ada4060fa746fe1884161f2267871da59101e67f84c457d082e67b01a7782c40d778723e5940b4e0e52f8542ecfaec8daa88b387eb15548349029b
7
+ data.tar.gz: 7bacb77e0c88b5fa9abea6c968d16413f0743fc44f498817eab72ce28b308ceca316f53241700204a7d1695e364214216c13ff0e1a869205b4f14d4b35e81584
data/LICENCE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2018 Richard Lapiš
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 all
13
+ 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 THE
21
+ SOFTWARE.
data/MIT-LICENCE ADDED
@@ -0,0 +1,20 @@
1
+ Copyright 2018 richard.lapis@gmail.com
2
+
3
+ Permission is hereby granted, free of charge, to any person obtaining
4
+ a copy of this software and associated documentation files (the
5
+ "Software"), to deal in the Software without restriction, including
6
+ without limitation the rights to use, copy, modify, merge, publish,
7
+ distribute, sublicense, and/or sell copies of the Software, and to
8
+ permit persons to whom the Software is furnished to do so, subject to
9
+ the following conditions:
10
+
11
+ The above copyright notice and this permission notice shall be
12
+ included in all copies or substantial portions of the Software.
13
+
14
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
15
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
17
+ NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
18
+ LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
19
+ OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
20
+ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
data/README.md CHANGED
@@ -47,6 +47,18 @@ RansackMemory::Core.config = {
47
47
  }
48
48
  ```
49
49
 
50
+ Available variables for `session_key_format`: `%controller_name%`, `%action_name%`, `%request_format%`, `%turbo_frame%` and `%path_params%`.
51
+
52
+ ### Nested resources
53
+
54
+ By default `/projects/1/tasks` and `/projects/2/tasks` share one saved filter and page number, because they are the same controller action. Add `%path_params%` to keep them separate (it interpolates dynamic route segments, e.g. `project_id-1`):
55
+
56
+ ```ruby
57
+ session_key_format: '%controller_name%_%action_name%_%request_format%_%path_params%'
58
+ ```
59
+
60
+ Beware that every parent record then gets its own entry in the session. With the default cookie session store (4 kB limit) prefer a server side session store.
61
+
50
62
  ## Load saved filters from another controller action
51
63
 
52
64
  In some cases, you want to load saved filters from another controller action. If so, you just create in the same controller this method:
@@ -56,7 +68,7 @@ In some cases, you want to load saved filters from another controller action. If
56
68
  'projects_index_html' if action_name == 'my_another_action'
57
69
  end
58
70
  ```
59
- this means that Ransack Memory load all filters that have been saved in action projects/index.html and load them into projects/my_another_action. This method must be public, not in private section!
71
+ this means that Ransack Memory load all filters that have been saved in action projects/index.html and load them into projects/my_another_action. The method can be public or private.
60
72
  Standard session key building is: ```"#{controller_name}_#{action_name}_#{request.format}"``` so you can load saved filters in any controller action like that.
61
73
 
62
74
  ## Kaminari issue
@@ -69,3 +81,10 @@ As an alternative update your kaminari view in `app/views/kaminari/_first_page.h
69
81
  <%= link_to_unless current_page.first?, t('views.pagination.first').html_safe, url_for(params.merge({page: 1, cancel_filter: nil})), remote: remote, class: 'btn btn-secondary' %>
70
82
  ```
71
83
  However beware that this will probably lead to problems in later Rails versions due to a change in the way it allows you to merge parameters.
84
+
85
+ ## Development
86
+
87
+ ```shell
88
+ bundle install
89
+ bundle exec rake test
90
+ ```
@@ -2,61 +2,121 @@ module RansackMemory
2
2
  module Concern
3
3
  extend ActiveSupport::Concern
4
4
 
5
- def save_and_load_filters
6
- user_set_key_identifier = respond_to?(:set_session_key_identifier) ? send(:set_session_key_identifier) : nil
7
-
8
- session_key_identifier = ::RansackMemory::Core.config[:session_key_format]
9
- .gsub('%controller_name%', controller_name)
10
- .gsub('%action_name%', action_name)
11
- .gsub('%request_format%', request.format.symbol.to_s)
5
+ DEFAULT_PARAM = :q
6
+ DEFAULT_SESSION_KEY_FORMAT = '%controller_name%_%action_name%_%request_format%'.freeze
7
+ SESSION_KEY_PREFIX = 'ranmemory'.freeze
8
+ # Variables coming from the request (header, URL) are cut to this length
9
+ # so that they can not blow up the session key.
10
+ MAX_KEY_PART_LENGTH = 100
12
11
 
13
- session_key_base = user_set_key_identifier.presence || "ranmemory_#{session_key_identifier}"
14
- session_key_base = "ranmemory_#{session_key_base}" unless session_key_base.starts_with?('ranmemory')
12
+ def save_and_load_filters
13
+ param_name = ransack_memory_config(:param, DEFAULT_PARAM)
14
+ filter_key = ransack_memory_session_key
15
+ page_key = "#{filter_key}_page"
16
+ per_page_key = "#{filter_key}_per_page"
15
17
 
16
- # permit search params
17
- params[::RansackMemory::Core.config[:param]].permit! if params[::RansackMemory::Core.config[:param]].present? && params[::RansackMemory::Core.config[:param]].respond_to?(:permit)
18
+ # Older versions kept one "last filter" shared by all controllers and
19
+ # actions. It is not used anymore, drop it to save space in the session.
20
+ session.delete(:last_q_params)
18
21
 
19
22
  # cancel filter if button pressed
20
- if params[:cancel_filter] == "true"
21
- session["#{session_key_base}"] = nil
22
- session["#{session_key_base}_page"] = nil
23
- session["#{session_key_base}_per_page"] = nil
23
+ if params[:cancel_filter].to_s == 'true'
24
+ [filter_key, page_key, per_page_key].each { |key| session.delete(key) }
25
+ # do not leak the flag into generated links (pagination, sort links)
26
+ params.delete(:cancel_filter)
24
27
  end
25
28
 
26
- # search term saving
27
- session["#{session_key_base}"] = params[::RansackMemory::Core.config[:param]].to_h if params[::RansackMemory::Core.config[:param]].present?
29
+ stored_filter = session[filter_key]
30
+ unless stored_filter.is_a?(Hash)
31
+ # a broken value would stay in the session forever
32
+ session.delete(filter_key) unless stored_filter.nil?
33
+ stored_filter = nil
34
+ end
35
+
36
+ submitted = params[param_name]
37
+ filter_changed = false
28
38
 
29
- # page number saving
30
- session["#{session_key_base}_page"] = params[:page] if params[:page].present?
39
+ if submitted.is_a?(ActionController::Parameters) && submitted.present?
40
+ # search term saving
41
+ submitted.permit!
42
+ new_filter = submitted.to_h.to_hash # plain Hash with string keys
43
+ # compared with the filter saved for THIS key, not with the last
44
+ # filter used anywhere in the application
45
+ filter_changed = stored_filter.nil? || stored_filter.to_hash != new_filter
46
+ session[filter_key] = new_filter
47
+ elsif submitted.blank? && stored_filter.present?
48
+ # search term load
49
+ params[param_name] = stored_filter.deep_dup
50
+ end
51
+ # A non-hash value (e.g. ?q=text used by a non-Ransack search) is left alone.
31
52
 
32
53
  # per page saving
33
- session["#{session_key_base}_per_page"] = params[:per_page] if params[:per_page].present?
54
+ per_page_changed = false
55
+ if params[:per_page].present?
56
+ per_page_changed = session[per_page_key].to_s != params[:per_page].to_s
57
+ session[per_page_key] = params[:per_page]
58
+ end
34
59
 
35
- # search term load
36
- params[::RansackMemory::Core.config[:param]] = session["#{session_key_base}"] if session["#{session_key_base}"].present?
60
+ if filter_changed || per_page_changed
61
+ # the saved page number belongs to the previous result set and may not
62
+ # exist in the new one - start from the first page
63
+ session.delete(page_key)
64
+ elsif params[:page].present?
65
+ # page number saving
66
+ session[page_key] = params[:page]
67
+ end
37
68
 
38
69
  # page number load
39
- params[:page] = session["#{session_key_base}_page"].presence
70
+ params[:page] = session[page_key].presence
40
71
 
41
72
  # per page load
42
- params[:per_page] = session["#{session_key_base}_per_page"].presence
73
+ params[:per_page] = session[per_page_key].presence
74
+ end
43
75
 
44
- # set page number to 1 if filter has changed
45
- if (params[::RansackMemory::Core.config[:param]].present? && session[:last_q_params] != params[::RansackMemory::Core.config[:param]].permit!.to_h) || (params[:cancel_filter].present? && session["#{session_key_base}_page"] != params[:page])
46
- params[:page] = nil
47
- session["#{session_key_base}_page"] = nil
76
+ # controller method, useful when you want to clear sessions when sign into another user
77
+ def clear_sessions
78
+ session.keys.each do |key|
79
+ session.delete(key) if key.to_s.start_with?(SESSION_KEY_PREFIX)
48
80
  end
81
+ session.delete(:last_q_params)
82
+ end
49
83
 
50
- session[:last_q_params] = params[::RansackMemory::Core.config[:param]]&.to_unsafe_h
84
+ private
51
85
 
52
- # session[:last_page] = params[:page]
86
+ def ransack_memory_config(name, default)
87
+ (::RansackMemory::Core.config || {})[name].presence || default
53
88
  end
54
89
 
55
- # controller method, useful when you want to clear sessions when sign into another user
56
- def clear_sessions
57
- session.keys.each do |key|
58
- session.delete(key) if key =~ /ranmemory_/
90
+ def ransack_memory_session_key
91
+ # set_session_key_identifier may be private in the controller
92
+ user_key = respond_to?(:set_session_key_identifier, true) ? send(:set_session_key_identifier) : nil
93
+ key = user_key.presence&.to_s || ransack_memory_default_session_key
94
+ key.start_with?(SESSION_KEY_PREFIX) ? key : "#{SESSION_KEY_PREFIX}_#{key}"
95
+ end
96
+
97
+ def ransack_memory_default_session_key
98
+ variables = {
99
+ 'controller_name' => controller_path.parameterize.underscore,
100
+ 'action_name' => action_name,
101
+ 'request_format' => request.format.try(:symbol).to_s,
102
+ 'turbo_frame' => (request.headers['Turbo-Frame'].presence || 'top').to_s[0, MAX_KEY_PART_LENGTH],
103
+ 'path_params' => ransack_memory_path_params
104
+ }
105
+
106
+ # One pass with a block: values are inserted literally (no backslash
107
+ # sequences) and are never interpolated again.
108
+ ransack_memory_config(:session_key_format, DEFAULT_SESSION_KEY_FORMAT).to_s.gsub(/%(\w+)%/) do |match|
109
+ variables.fetch(Regexp.last_match(1), match)
59
110
  end
60
111
  end
112
+
113
+ # Dynamic segments of the current route, e.g. "project_id-5" for
114
+ # /projects/5/tasks. Lets nested resources keep a filter per parent record.
115
+ def ransack_memory_path_params
116
+ request.path_parameters.except(:controller, :action, :format)
117
+ .sort_by { |name, _| name.to_s }
118
+ .map { |name, value| "#{name}-#{value}" }
119
+ .join('_')[0, MAX_KEY_PART_LENGTH]
120
+ end
61
121
  end
62
122
  end
@@ -1,5 +1,9 @@
1
1
  module RansackMemoryHelper
2
2
  def clear_filter(opts = {})
3
+ opts = opts.dup
4
+ # The link changes the session with a GET request. Turbo prefetches links
5
+ # on hover, which would cancel the filter without a click.
6
+ opts[:data] = { turbo_prefetch: false }.merge(opts[:data] || {})
3
7
  render 'shared/ransack_memory_clear_filter', opts: opts
4
8
  end
5
- end
9
+ end
@@ -5,8 +5,8 @@ if defined?(Rails)
5
5
  source_root(File.expand_path(File.dirname(__FILE__) + "/../templates/ransack_memory"))
6
6
  def copy_initializer
7
7
 
8
- copy_file 'ransack_memory_template.rb', 'config/initializers/ransack_memory.rb'
8
+ template 'ransack_memory_template.rb', 'config/initializers/ransack_memory.rb'
9
9
  end
10
10
  end
11
11
 
12
- end
12
+ end
@@ -1,3 +1,3 @@
1
1
  module RansackMemory
2
- VERSION = '0.1.0'
2
+ VERSION = '1.0.0'
3
3
  end
@@ -1,4 +1,19 @@
1
1
  RansackMemory::Core.config = {
2
- param: :q, # this means the default Ransack param name for searching. You can change it
3
- session_key_format: '%controller_name%_%action_name%_%request_format%' # this means how the key used to store the information to the session will be stored. Currently it interpolates request parameters. You can customize it and use these vars to build a key that fits your needs
2
+ # This means the default Ransack param name for searching. You can change it
3
+ param: :q,
4
+
5
+ # This means how the key used to store the information to the session
6
+ # will be stored. Currently it interpolates request parameters.
7
+ # You can customize it and use these vars to build a key that fits your needs
8
+ #
9
+ # Available variables are:
10
+ # controller_name
11
+ # action_name
12
+ # request_format
13
+ # turbo_frame
14
+ <% if defined? Turbo -%>
15
+ session_key_format: '%controller_name%_%action_name%_%request_format%_%turbo_frame%'
16
+ <% else -%>
17
+ session_key_format: '%controller_name%_%action_name%_%request_format%'
18
+ <% end -%>
4
19
  }
metadata CHANGED
@@ -1,21 +1,23 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: ransack_memory
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.1.0
4
+ version: 1.0.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - Richard Lapiš
8
- autorequire:
9
8
  bindir: bin
10
9
  cert_chain: []
11
- date: 2018-06-25 00:00:00.000000000 Z
10
+ date: 1980-01-02 00:00:00.000000000 Z
12
11
  dependencies: []
13
- description: Automatically save and load ransack's filtered params into session
12
+ description: Remembers Ransack search params, page number and per page value in the
13
+ Rails session for each controller action and loads them back on the next visit.
14
14
  email: richard.lapis@gmail.com
15
15
  executables: []
16
16
  extensions: []
17
17
  extra_rdoc_files: []
18
18
  files:
19
+ - LICENCE
20
+ - MIT-LICENCE
19
21
  - README.md
20
22
  - app/controllers/concerns/ransack_memory/concern.rb
21
23
  - app/helpers/ransack_memory_helper.rb
@@ -29,8 +31,9 @@ files:
29
31
  homepage: https://github.com/richardrails/ransack_memory
30
32
  licenses:
31
33
  - MIT
32
- metadata: {}
33
- post_install_message:
34
+ metadata:
35
+ source_code_uri: https://github.com/richardrails/ransack_memory
36
+ bug_tracker_uri: https://github.com/richardrails/ransack_memory/issues
34
37
  rdoc_options: []
35
38
  require_paths:
36
39
  - lib
@@ -38,16 +41,14 @@ required_ruby_version: !ruby/object:Gem::Requirement
38
41
  requirements:
39
42
  - - ">="
40
43
  - !ruby/object:Gem::Version
41
- version: 1.9.3
44
+ version: '2.5'
42
45
  required_rubygems_version: !ruby/object:Gem::Requirement
43
46
  requirements:
44
47
  - - ">="
45
48
  - !ruby/object:Gem::Version
46
49
  version: '0'
47
50
  requirements: []
48
- rubyforge_project:
49
- rubygems_version: 2.6.13
50
- signing_key:
51
- specification_version: 3
51
+ rubygems_version: 3.6.9
52
+ specification_version: 4
52
53
  summary: Automatically save and load ransack's filtered params into session
53
54
  test_files: []