diff --git a/README.md b/README.md
index 744264c..3717c08 100644
--- a/README.md
+++ b/README.md
@@ -28,6 +28,9 @@ filter :created_at, as: :date_time_range,
floors on two-ended filters.
* [`message:`](#value-policies-sanitize-and-validate) and plain-i18n defaults for every
violation text.
+* [`none:` / `present:`](#none-and-present-options) - None and Present options on a select
+ filter, and None and Present predicates on a string or numeric one, for the records whose
+ attribute is empty and the ones where it is not.
* [`default_filters_notice`](#telling-the-admin-why) - the flash that tells the admin why the
page shows a slice; [`require_any_filter`](#resource-level-guard) - an index that waits to
be asked.
@@ -336,6 +339,138 @@ lands in `flash[:error]` (and rides the redirect), and the filter's declared `de
any - refills through the ordinary merge. The defaults notice stays quiet on that render:
the error already explains why the page shows the default slice.
+## None and Present options
+
+A select filter cannot ask for the records whose attribute is empty, or for the ones where it
+holds anything at all: no value of its collection means either. `none:` and `present:` add the
+options, first in the list after the blank one, None before Present:
+
+```ruby
+filter :account, as: :select, collection: proc { Account.order(:name) },
+ extensions: { none: true, present: true }
+filter :status, as: :select, multiple: true, collection: %w[draft published],
+ extensions: { none: "No status" } # the option's label
+```
+
+`true` labels the option from the i18n keys `active_admin_filter_extensions.none` ("None") and
+`active_admin_filter_extensions.present` ("Present"); a String is the label itself. None
+searches `_null` on the filter's attribute, Present searches `_not_null`. On a multiple select:
+
+* None beside other values searches "any of these, or empty".
+* Present beside other values searches Present alone: every value is a present one.
+* None and Present together search every record, so no condition is applied.
+
+The select submits a marker under its own key - `q[account_id_eq]=__none__` or
+`q[account_id_eq]=__present__` - and only the search is handed the condition. The URL, the form
+and the other extensions read the request as submitted: `required:` counts either option as an
+answer, `sanitize:` and `validate:` are not handed the marker, and
+`default: -> { ActiveAdminFilterExtensions.none_value }` opens the index on the empty records.
+The Current Filters panel shows the label: "Account equals None", "Account equals Present".
+Move a marker where a real value could spell the same thing:
+
+```ruby
+ActiveAdminFilterExtensions.none_value = "__empty__"
+ActiveAdminFilterExtensions.present_value = "__filled__"
+```
+
+### On a string or numeric filter
+
+A `:string` or `:numeric` filter that picks its predicate from a dropdown takes the same two
+options, as two more predicates closing the list:
+
+```ruby
+filter :title, extensions: { none: true, present: true }
+filter :position, as: :numeric, extensions: { none: "No position" }
+```
+
+A string filter searches `_blank` and `_present`, so an empty string counts as none; a numeric
+one searches `_null` and `_not_null`. These are Ransack's own predicates and the URL says them
+as they are searched: `q[title_blank]=1`. `required:` counts them as an answer, `sanitize:` and
+`validate:` are not handed the `1`, and the Current Filters panel reads "Title equals None".
+A default such as `default: { blank: "1" }` is not handed to them either.
+
+So the same string column splits differently on a select and in the dropdown. Ransack does not
+trim, so a value of only spaces counts as present:
+
+| `title` | Select None (`_null`) | Select Present (`_not_null`) | Dropdown None (`_blank`) | Dropdown Present (`_present`) |
+| --- | --- | --- | --- | --- |
+| `"john"` | | yes | | yes |
+| `""` | | yes | yes | |
+| `" "` | | yes | | yes |
+| `NULL` | yes | | yes | |
+
+Such a predicate has nothing to type, and Active Admin leaves an empty box out of the submit.
+The gem's script fills the box and hides it. Without the script the two predicates filter
+nothing, so load it on every page with a filters form.
+
+Active Admin 3 (Sprockets), in `app/assets/javascripts/active_admin.js`:
+
+```javascript
+//= require active_admin_filter_extensions
+```
+
+Active Admin 4 (import map): the gem pins the module `active_admin_filter_extensions` into
+`ActiveAdmin.importmap`. If your Active Admin has the `javascript_modules` setting, the gem adds
+itself to it and pages import it automatically. Otherwise override
+`app/views/active_admin/_html_head.html.erb` (copy it from Active Admin) and add after the
+`javascript_importmap_tags` line:
+
+```erb
+<%= javascript_import_module_tag "active_admin_filter_extensions" %>
+```
+
+If you use active_admin_theme 4, add the module to its list in an initializer instead:
+
+```ruby
+ActiveAdminTheme.javascripts += %w[active_admin_filter_extensions]
+```
+
+The script listens on `document`, so it does not depend on the order it is loaded in. For a
+filters form the page inserts on its own, call `ActiveAdminFilterExtensions.sync(form)`.
+
+Any other filter raises on `none:` or `present:`: check boxes, a date range, a select that
+submits `_not_eq` or `_not_in`, a string filter named after its predicate (`filter :title_cont`).
+
+### Styling the options
+
+The gem ships no CSS. Every option it adds, to a select or to a predicate dropdown, carries
+classes and a data attribute to style:
+
+```html
+None
+Present
+```
+
+A Hash gives the option classes of its own beside the label, appended to the gem's:
+
+```ruby
+filter :account, as: :select,
+ extensions: { none: { label: "No account", class: "text-red-700 italic" },
+ present: { class: "font-bold" } }
+```
+
+```css
+.filter-extensions-none { font-style: italic; }
+[data-filter-extensions-option] { color: #b91c1c; }
+```
+
+A browser styles an `` only so far. A Tom Select widget - the active_admin_theme
+searchable select - copies the option's classes onto the option it renders in the dropdown and
+onto the selected item, so the same selectors style both.
+
+### Dependent selects
+
+A dependent select - the active_admin_theme searchable select with `depends_on:`, say - sends
+its parent's value to its options endpoint, so that endpoint is sent the marker too. It is
+applied there when the endpoint is an Active Admin index that declares the same filter with
+`none:` or `present:`. An endpoint that searches `q` on its own is handed the marker as a plain
+value, and can have it rewritten:
+
+```ruby
+markers = ActiveAdminFilterExtensions.markers # { none: "__none__", present: "__present__" }
+q = ActiveAdminFilterExtensions::MarkerOptions.search_params(q, %w[account_id_eq], markers[:none], markers[:present])
+```
+
## The redirect
A bare visit to the index redirects once to itself with the effective filters spelled out in
@@ -372,7 +507,8 @@ Four prints in small type:
## Active Admin 4
-The gem works on Active Admin 3.5 and 4 from the same release; it ships no JavaScript or CSS.
+The gem works on Active Admin 3.5 and 4 from the same release. It ships no CSS, and one
+script, which only the [None and Present predicates](#on-a-string-or-numeric-filter) need.
On Active Admin 4 the filters section keeps Active Admin's own `h3.filters-form-title`, and
the Current Filters section (`#active_search_sidebar_section`) also shows when only defaults
apply. Page objects can select the filters form by `[data-filter-extensions-form]` and, on
diff --git a/app/assets/javascripts/active_admin_filter_extensions.js b/app/assets/javascripts/active_admin_filter_extensions.js
new file mode 100644
index 0000000..7621506
--- /dev/null
+++ b/app/assets/javascripts/active_admin_filter_extensions.js
@@ -0,0 +1,70 @@
+// Plain script with no imports or exports, so the same file runs as a classic script (Sprockets
+// on Active Admin 3) and as an ES module (the import map on Active Admin 4).
+//
+// A None or Present choice in a filter's predicate dropdown has nothing to type, and Active
+// Admin does not submit an empty box. So the box of such a predicate holds "1" - what the
+// predicate is answered with - and is hidden. Active Admin's own handler renames the box after
+// the predicate; this one does too, as a page the browser restores fires no change event. A held
+// box turns type="hidden", so the host's min, max or pattern cannot block the submit.
+(function () {
+ if (window.ActiveAdminFilterExtensions) { return; }
+
+ var PREDICATE = "option[data-filter-extensions-predicate]";
+ var HELD = "data-filter-extensions-held";
+ // Ransack's false values: a restored predicate answered with one searches the opposite.
+ var FALSE = /^(0|f|false|n|no|off)$/i;
+
+ // The box Active Admin renames: the first input after the dropdown. A select widget may sit
+ // between the two.
+ function boxOf(select) {
+ var sibling = select.nextElementSibling;
+ while (sibling && !sibling.matches("input")) { sibling = sibling.nextElementSibling; }
+ return sibling;
+ }
+
+ // chosen: the admin just picked the predicate, so its answer is "1" whatever the box held.
+ function syncSelect(select, chosen) {
+ if (!select.querySelector(PREDICATE)) { return; }
+ var box = boxOf(select);
+ if (!box) { return; }
+
+ var name = "q[" + select.value + "]";
+ var restored = !chosen && box.name === name && FALSE.test(box.value);
+ if (select.value) { box.name = name; }
+ var option = select.options[select.selectedIndex];
+ if (option && option.matches(PREDICATE)) {
+ if (!box.hasAttribute(HELD)) { box.setAttribute(HELD, box.type); }
+ box.type = "hidden";
+ if (!restored) { box.value = "1"; }
+ } else if (box.hasAttribute(HELD)) {
+ box.type = box.getAttribute(HELD) || "text";
+ box.value = "";
+ box.removeAttribute(HELD);
+ }
+ }
+
+ function sync(root) {
+ var scope = root && root.querySelectorAll ? root : document;
+ Array.prototype.forEach.call(scope.querySelectorAll("select"), function (select) { syncSelect(select, false); });
+ }
+
+ // Delegated, so a form rendered after this script ran is covered too.
+ document.addEventListener("change", function (event) {
+ var select = event.target;
+ if (select && select.matches && select.matches("select")) { syncSelect(select, true); }
+ });
+
+ // In the capture phase, ahead of Active Admin's handler that disables the empty fields: a
+ // form that arrived without any of the events below is still submitted with its box filled.
+ document.addEventListener("submit", function (event) { sync(event.target); }, true);
+
+ // A form restored after a submit, whichever way the page arrived.
+ ["DOMContentLoaded", "turbo:load", "turbo:render", "turbo:frame-load", "turbolinks:load"].forEach(function (name) {
+ document.addEventListener(name, function () { sync(document); });
+ });
+ window.addEventListener("pageshow", function () { sync(document); });
+ if (document.readyState !== "loading") { sync(document); }
+
+ // For a filters form the application inserts itself: ActiveAdminFilterExtensions.sync(form).
+ window.ActiveAdminFilterExtensions = { sync: sync };
+})();
diff --git a/config/importmap.rb b/config/importmap.rb
new file mode 100644
index 0000000..9d112d5
--- /dev/null
+++ b/config/importmap.rb
@@ -0,0 +1,4 @@
+# frozen_string_literal: true
+
+# Pinned into ActiveAdmin.importmap, the map the Active Admin 4 layout renders.
+pin "active_admin_filter_extensions", to: "active_admin_filter_extensions.js", preload: false
diff --git a/config/locales/en.yml b/config/locales/en.yml
index 403dc48..c9269da 100644
--- a/config/locales/en.yml
+++ b/config/locales/en.yml
@@ -8,3 +8,7 @@ en:
before_floor: "%{filter} filter cannot start before %{floor}."
given_together: "%{filters} filters must be given together."
require_any_filter: "You must specify at least one filter"
+ # The labels of a select filter's None and Present options
+ # (`extensions: { none: true, present: true }`).
+ none: "None"
+ present: "Present"
diff --git a/lib/active_admin_filter_extensions.rb b/lib/active_admin_filter_extensions.rb
index 5fd4522..29d9d60 100644
--- a/lib/active_admin_filter_extensions.rb
+++ b/lib/active_admin_filter_extensions.rb
@@ -12,10 +12,12 @@
require "active_admin_filter_extensions/search_keys"
require "active_admin_filter_extensions/required_filters"
require "active_admin_filter_extensions/filter_defaults"
+require "active_admin_filter_extensions/marker_options"
require "active_admin_filter_extensions/filters_form"
require "active_admin_filter_extensions/redirect"
require "active_admin_filter_extensions/policies"
require "active_admin_filter_extensions/notice"
+require "active_admin_filter_extensions/engine"
module ActiveAdminFilterExtensions
class << self
@@ -33,6 +35,26 @@ def notice_flash_key
@notice_flash_key ||= :notice
end
+ # What the None option of a select filter submits (`extensions: { none: true }`). Move it
+ # where a real value of a filtered column could spell the same thing.
+ attr_writer :none_value
+
+ def none_value
+ @none_value ||= "__none__"
+ end
+
+ # What the Present option submits (`extensions: { present: true }`).
+ attr_writer :present_value
+
+ def present_value
+ @present_value ||= "__present__"
+ end
+
+ # @return [Hash] :none / :present => what that option submits
+ def markers
+ { none: none_value, present: present_value }
+ end
+
# Active Admin 4 moved the filters form helper and the Current Filters section.
def aa_v4?
return @aa_v4 if defined?(@aa_v4)
@@ -58,8 +80,10 @@ def warning_flash_key
ActiveAdmin::ResourceController.include ActiveAdminFilterExtensions::SearchKeys
ActiveAdmin::ResourceController.include ActiveAdminFilterExtensions::RequiredFilters
ActiveAdmin::ResourceController.include ActiveAdminFilterExtensions::FilterDefaults
+ ActiveAdmin::ResourceController.include ActiveAdminFilterExtensions::MarkerOptions
ActiveAdmin::ResourceController.helper_method :filtering_params, :applied_filter_params,
- :filter_default_values, :visible_filters
+ :filter_default_values, :visible_filters,
+ :marker_filter_form_options
ActiveAdmin::ResourceDSL.include ActiveAdminFilterExtensions::Policies::ResourcePolicyDSL
ActiveAdmin::Resource.include ActiveAdminFilterExtensions::Policies::ResourcePolicySettings
@@ -69,6 +93,9 @@ def warning_flash_key
# decision - and therefore the URL - is computed from.
ActiveAdmin::ResourceController.include ActiveAdminFilterExtensions::Policies::Controller
ActiveAdmin::ResourceController.include ActiveAdminFilterExtensions::Redirect
+ ActiveAdmin::Filters::Active.prepend ActiveAdminFilterExtensions::CurrentFilters
+ ActiveAdmin::Inputs::Filters::StringInput.prepend ActiveAdminFilterExtensions::PredicateSelect
+ ActiveAdmin::Inputs::Filters::NumericInput.prepend ActiveAdminFilterExtensions::PredicateSelect
if ActiveAdminFilterExtensions.aa_v4?
ActiveAdmin::Resource.prepend ActiveAdminFilterExtensions::ResourceExtensionV4
ActiveAdmin::FormHelper.prepend ActiveAdminFilterExtensions::ViewHelper
diff --git a/lib/active_admin_filter_extensions/data_access.rb b/lib/active_admin_filter_extensions/data_access.rb
index feb3839..753df8e 100644
--- a/lib/active_admin_filter_extensions/data_access.rb
+++ b/lib/active_admin_filter_extensions/data_access.rb
@@ -3,12 +3,14 @@
module ActiveAdminFilterExtensions
# The single method this gem replaces: Active Admin searches the collection on `params[:q]`
# read directly, and it searches #filtering_params instead. Everything that method means is
- # in FilterDefaults.
+ # in FilterDefaults. A None or Present option's marker becomes its condition here and no
+ # earlier - see MarkerOptions.
module DataAccess
protected
def apply_filtering(chain)
- @search = chain.ransack(filtering_params, **filter_ransack_options)
+ @search = chain.ransack(marker_filter_search_params(filtering_params), **filter_ransack_options)
+ label_marker_filters(@search)
# An :empty policy keeps the request intact - the form still shows what the admin
# typed - and blanks the collection instead.
return @search.result.none if filter_policy_render_empty?
diff --git a/lib/active_admin_filter_extensions/engine.rb b/lib/active_admin_filter_extensions/engine.rb
new file mode 100644
index 0000000..0302207
--- /dev/null
+++ b/lib/active_admin_filter_extensions/engine.rb
@@ -0,0 +1,33 @@
+# frozen_string_literal: true
+
+module ActiveAdminFilterExtensions
+ JAVASCRIPT_MODULE = "active_admin_filter_extensions"
+
+ # Serves the gem's one script, app/assets/javascripts/active_admin_filter_extensions.js. An
+ # engine's app/assets is on the asset paths, which is all Sprockets needs on Active Admin 3
+ # and all Propshaft needs on Active Admin 4.
+ class Engine < ::Rails::Engine
+ # Active Admin 4 renders an import map of its own, so the module is pinned there.
+ initializer "active_admin_filter_extensions.importmap", after: "active_admin.importmap" do |app|
+ next unless ActiveAdminFilterExtensions.aa_v4? && app.config.respond_to?(:importmap)
+
+ ActiveAdmin.importmap.draw(root.join("config", "importmap.rb"))
+ end
+
+ # The import map resolves every pin, and Sprockets raises for a file outside the precompile
+ # list. Propshaft has no such list.
+ initializer "active_admin_filter_extensions.precompile", group: :all do |app|
+ next unless ActiveAdminFilterExtensions.aa_v4? && app.config.respond_to?(:assets)
+
+ precompile = app.config.assets.precompile
+ precompile << "#{JAVASCRIPT_MODULE}.js" if precompile.is_a?(Array)
+ end
+
+ # javascript_modules is pending upstream (activeadmin/activeadmin#9148).
+ config.after_initialize do
+ if ActiveAdmin.application.respond_to?(:javascript_modules)
+ ActiveAdmin.application.javascript_modules |= [JAVASCRIPT_MODULE]
+ end
+ end
+ end
+end
diff --git a/lib/active_admin_filter_extensions/filter_defaults.rb b/lib/active_admin_filter_extensions/filter_defaults.rb
index e08a271..a2e28eb 100644
--- a/lib/active_admin_filter_extensions/filter_defaults.rb
+++ b/lib/active_admin_filter_extensions/filter_defaults.rb
@@ -199,20 +199,26 @@ def validate_default_against_value_policies(attribute, options, result, keys)
validator = options[:validate]
return unless sanitizer || validator
+ # A boolean predicate the filter does not derive itself goes unpoliced when submitted
+ # (#sibling_predicate_keys), so as a default it is not judged either.
+ declared = policy_search_keys(attribute, options).map(&:to_s)
keys.each do |key|
value = result[key]
next if value.nil?
+ next if boolean_predicate?(key) && !declared.include?(key.to_s)
+
+ exempt = policy_exempt_markers(attribute, options, key)
# Judged the way the URL will say it: a scalar as the String it becomes, an Array
# element by element - the shape a multi-valued input submits.
if sanitizer
resolved = Policies::Sanitizers.resolve(sanitizer)
- result[key] = sanitize_default_value(attribute, resolved, value)
+ result[key] = sanitize_default_value(attribute, resolved, value, exempt)
end
next unless validator
resolved_validator = Policies::Validators.resolve(validator)
- next unless default_value_strings(result[key])
+ next unless (default_value_strings(result[key]) - exempt)
.any? { |string| ::MethodOrProcHelper.render_in_context(self, resolved_validator, string) }
raise ArgumentError,
@@ -233,9 +239,9 @@ def default_value_strings(value)
Array.wrap(value).map(&:to_s).reject(&:blank?)
end
- def sanitize_default_value(attribute, sanitizer, value)
- return value.map { |element| sanitize_default_value(attribute, sanitizer, element) } if value.is_a?(Array)
- return value if value.is_a?(Enumerable)
+ def sanitize_default_value(attribute, sanitizer, value, exempt = [])
+ return value.map { |element| sanitize_default_value(attribute, sanitizer, element, exempt) } if value.is_a?(Array)
+ return value if value.is_a?(Enumerable) || exempt.include?(value)
sanitized = ::MethodOrProcHelper.render_in_context(self, sanitizer, value.to_s.dup).to_s
# The same fixpoint check submitted values face: without it the CSV searches the
diff --git a/lib/active_admin_filter_extensions/filter_options.rb b/lib/active_admin_filter_extensions/filter_options.rb
index 11b1a01..adc1ddf 100644
--- a/lib/active_admin_filter_extensions/filter_options.rb
+++ b/lib/active_admin_filter_extensions/filter_options.rb
@@ -10,7 +10,7 @@ module FilterOptions
# `:if` / `:unless` are Active Admin's but are resolved by #visible_filters before the
# form is given anything.
NOT_FOR_INPUT = %i[extensions if unless].freeze
- EXTENSION_KEYS = %i[default required with sanitize validate on_invalid max_range min message].freeze
+ EXTENSION_KEYS = %i[default required with sanitize validate on_invalid max_range min message none present].freeze
# required: and min: are documented Formtastic input options in their own right. The gem
# answers to them only INSIDE extensions:, so flat they are the host's: no stray-key raise,
# no policy, straight through to the input.
diff --git a/lib/active_admin_filter_extensions/filters_form.rb b/lib/active_admin_filter_extensions/filters_form.rb
index 8376428..fecc2f5 100644
--- a/lib/active_admin_filter_extensions/filters_form.rb
+++ b/lib/active_admin_filter_extensions/filters_form.rb
@@ -54,7 +54,89 @@ def active_search_sidebar_section
# method, so that this gem carries no copy of a method body that belongs to Active Admin.
module ViewHelper
def active_admin_filters_form_for(search, filters, options = {})
- super(search, filters.transform_values { |opts| FilterOptions.input_options(opts) }, options)
+ filters = filters.to_h do |attribute, opts|
+ # Asked of the controller only for a none: or present: filter - the helper exists on
+ # resource pages, and this method is also mixed into views that are not one.
+ opts = marker_filter_form_options(attribute, opts, search, self) if opts[:none] || opts[:present]
+ [attribute, FilterOptions.input_options(opts)]
+ end
+ super(search, filters, options)
+ end
+ end
+
+ # The predicate dropdown of a :string or :numeric filter that declares none: or present:.
+ # Active Admin labels every predicate with Ransack's translation - "Is blank" - and the box
+ # with the search's value, a "true". Prepended to both inputs.
+ module PredicateSelect
+ def filter_options
+ items = options[MarkerOptions::PREDICATE_ITEMS]
+ return super unless items
+
+ super.map { |item| items.fetch(item.last, item) }
+ end
+
+ # What the gem's script writes into the box of such a predicate, so that a form restored
+ # after the submit says the same before the script has run. A false answer searches the
+ # opposite and is kept, or the next submit would reverse the search.
+ def input_html_options
+ items = options[MarkerOptions::PREDICATE_ITEMS]
+ return super unless items&.key?(current_filter)
+
+ html = super
+ ::Ransack::Constants::FALSE_VALUES.include?(html[:value]) ? html : html.merge(value: "1")
+ end
+ end
+
+ # Current Filters lists the search's top-level conditions. A None option is a `_null` there,
+ # reading "is null 1", and a Present option a `_not_null` - and None beside other values is in
+ # an OR grouping, which is not listed at all. Prepended to ActiveAdmin::Filters::Active, the
+ # one class both versions list from.
+ module CurrentFilters
+ def initialize(resource, search)
+ super
+ labels = search.instance_variable_get(MarkerOptions::LABELS)
+ return if labels.blank?
+
+ filters.each { |filter| name_marker_filter(filter, labels[filter.condition.key]) }
+ search.base.groupings.each do |grouping|
+ marker = grouping.conditions.find { |condition| labels.key?(condition.key) }
+ next unless marker
+
+ (grouping.conditions - [marker]).each do |condition|
+ filters << name_marker_filter(build_filters([condition]).first, labels[marker.key])
+ end
+ end
+ end
+
+ private
+
+ def name_marker_filter(filter, label)
+ return filter unless label
+
+ filter.extend(MarkerActiveFilter).marker_label = label
+ filter
+ end
+ end
+
+ # One Current Filters entry of a None or Present option: "Account equals None" or "Title
+ # equals Present" for the condition alone, "Status in None and draft" for the values chosen
+ # beside None.
+ module MarkerActiveFilter
+ attr_writer :marker_label
+
+ def values
+ [@marker_label] + (marker_alone? ? [] : super.to_a)
+ end
+
+ def predicate_name
+ marker_alone? ? ::Ransack::Translate.predicate("eq") : super
+ end
+
+ private
+
+ # The option's own condition is answered by a boolean; the values beside None are not.
+ def marker_alone?
+ condition.predicate.type == :boolean
end
end
diff --git a/lib/active_admin_filter_extensions/marker_options.rb b/lib/active_admin_filter_extensions/marker_options.rb
new file mode 100644
index 0000000..e5a4027
--- /dev/null
+++ b/lib/active_admin_filter_extensions/marker_options.rb
@@ -0,0 +1,242 @@
+# frozen_string_literal: true
+
+require "active_support/core_ext/array/wrap"
+
+module ActiveAdminFilterExtensions
+ # `extensions: { none: true, present: true }` - a select filter's options for the records
+ # whose attribute is empty, and for the ones where it is not. The select submits a marker
+ # under its own key and only the search is handed the `_null` or `_not_null` it stands for,
+ # so defaults, policies and the redirect read the request as submitted.
+ #
+ # On a :string or :numeric filter that picks its predicate from a dropdown, the two are
+ # predicates added to that dropdown. Those are Ransack's own and are submitted as they are
+ # searched - `q[title_blank]=1` - by the gem's script, which fills the box Active Admin would
+ # otherwise leave out of the request for being empty.
+ module MarkerOptions
+ # What a select derives. _not_eq and _not_in end the same way, and an OR beside their
+ # `_not_null` is no reading of "none of these".
+ KEY = /(? what that option submits
+ # @return [Array] the options picked in `value`
+ def self.chosen(value, markers)
+ values = Array.wrap(value)
+ markers.select { |_kind, marker| values.include?(marker) }.keys
+ end
+
+ # @param keys [Array] the search keys whose select carries the options
+ # @return [Hash] the search values, every marker under `keys` turned into its condition
+ def self.search_params(params, keys, none, present = nil)
+ # rewrite merges the String key "g"; a Symbol :g would sit beside it.
+ params = params.transform_keys(&:to_s) if params.is_a?(Hash)
+ markers = { none: none, present: present }.compact
+ rewrite(params, keys.to_h { |key| [key.to_s, markers] })
+ end
+
+ # @param markers [Hash] search key => the { none:, present: } markers its filter declares
+ def self.rewrite(params, markers)
+ groupings = []
+ searched = params.each_with_object({}) do |(key, value), result|
+ declared = markers[key.to_s] || {}
+ chosen = MarkerOptions.chosen(value, declared)
+ next result[key] = value if chosen.empty?
+ # Empty or not is every record: the two options together ask nothing of the attribute.
+ next if chosen.size == 2
+ # Every value is a present one, so the values chosen beside Present narrow nothing.
+ next result[predicate_key(key, :present)] = "1" if chosen == [:present]
+
+ null_key = predicate_key(key, :none)
+ values = (Array.wrap(value) - declared.values).reject { |element| element.blank? && element != false }
+ next result[null_key] = "1" if values.empty?
+
+ # "None or Acme" is an OR, and Ransack only says OR inside a grouping.
+ groupings << { "m" => "or", key.to_s => values, null_key => "1" }
+ end
+ return searched if groupings.empty?
+
+ existing = searched["g"]
+ existing = existing.values if existing.is_a?(Hash)
+ searched.merge("g" => Array(existing) + groupings)
+ end
+
+ protected
+
+ # What Ransack is handed in place of #filtering_params.
+ def marker_filter_search_params(params)
+ return params if marker_filter_keys.empty?
+
+ declared = marker_filter_keys.to_h { |attribute, key| [key, declared_markers(visible_filters[attribute])] }
+ MarkerOptions.rewrite(params, declared)
+ end
+
+ # The Current Filters panel is built from the search object alone, so the label of every
+ # option this request searched rides on it, under the key of the condition it became.
+ def label_marker_filters(search)
+ labels = marker_filter_keys.each_with_object({}) do |(attribute, key), result|
+ options = visible_filters[attribute]
+ chosen = MarkerOptions.chosen(marker_filter_request_value(key), declared_markers(options))
+ # None and Present together became no condition, and the panel lists conditions.
+ next unless chosen.size == 1
+
+ result[MarkerOptions.predicate_key(key, chosen.first)] = marker_option(options, chosen.first)[:label]
+ end
+ marker_filters[:predicates].each do |attribute, predicates|
+ predicates.each do |kind, predicate|
+ key = "#{attribute}_#{predicate}"
+ # Answered with a false, the predicate searches its opposite and reads as Ransack's.
+ next unless ::Ransack::Constants::TRUE_VALUES.include?(marker_filter_request_value(key))
+
+ labels[key] = marker_option(visible_filters[attribute], kind)[:label]
+ end
+ end
+ search.instance_variable_set(LABELS, labels) if labels.any?
+ end
+
+ # A filter's options with its None and Present options heading the collection. The
+ # collection is asked of an input built on the form's own search and view, so a Proc, a
+ # relation and a filter with no collection: resolve the way the form resolves them.
+ def marker_filter_form_options(attribute, options, search, template)
+ key = marker_filter_keys[attribute.to_sym]
+ return marker_predicate_form_options(attribute, options) unless key
+
+ builder = ::ActiveAdmin::Filters::FormBuilder.new(:q, search, template, {})
+ collection = build_filter_input(attribute, options, builder).collection
+ if collection.is_a?(String)
+ raise ArgumentError, "filter :#{attribute} declares #{declared_marker_names(options)} but its collection " \
+ "is rendered HTML - the option needs a collection of values to head"
+ end
+
+ markers = declared_markers(options)
+ heading = markers.map { |kind, marker| marker_option_item(marker_option(options, kind), kind, marker) }
+ # The collection is pairs by now, and member_label:/member_value: would be sent to them.
+ options = options.except(:member_label, :member_value).merge(collection: heading + collection.to_a)
+ # Ransack is never handed a marker, and the values chosen beside None sit in a grouping,
+ # so the search object cannot say what is selected - the request can.
+ requested = marker_filter_request_value(key)
+ MarkerOptions.chosen(requested, markers).any? ? options.merge(selected: requested) : options
+ end
+
+ private
+
+ # A dropdown filter's options with None and Present closing its list of predicates. The
+ # items ride beside the list, for PredicateSelect to render in place of Active Admin's.
+ def marker_predicate_form_options(attribute, options)
+ predicates = marker_filters[:predicates][attribute.to_sym]
+ return options unless predicates
+
+ items = predicates.to_h do |kind, predicate|
+ key = "#{attribute}_#{predicate}"
+ [key, marker_option_item(marker_option(options, kind), kind, key, PREDICATE_DATA => kind.to_s)]
+ end
+ filters = build_filter_input(attribute, options).filters | predicates.values.map(&:to_sym)
+ options.merge(filters: filters, PREDICATE_ITEMS => items)
+ end
+
+ # @return [Hash] filter attribute => search key, for the select filters
+ def marker_filter_keys
+ marker_filters[:selects]
+ end
+
+ # Every visible none: or present: filter, by where its options go: under a select's search
+ # key, or into a dropdown as predicates. Materialized on every index request, which is also
+ # what refuses, loudly, a filter the options cannot work on.
+ #
+ # @return [Hash] :selects => { attribute => search key },
+ # :predicates => { attribute => { none: / present: => predicate } }
+ def marker_filters
+ @marker_filters ||= visible_filters.each_with_object({ selects: {}, predicates: {} }) do |(attribute, options), result|
+ declared = declared_markers(options).keys
+ next if declared.empty?
+
+ validate_marker_options(attribute, options)
+ keys = filter_search_keys(attribute, options)
+ input = build_filter_input(attribute, options)
+ if input.is_a?(::Formtastic::Inputs::SelectInput) && keys.size == 1 && keys.first.match?(KEY)
+ result[:selects][attribute.to_sym] = keys.first
+ elsif (predicates = dropdown_predicates(input))
+ result[:predicates][attribute.to_sym] = predicates.slice(*declared)
+ else
+ raise ArgumentError, "filter :#{attribute} declares #{declared_marker_names(options)} but its " \
+ "#{input.as} input submits #{keys.join(' and ')} - a None or Present " \
+ "option needs a select that submits _eq or _in, or a :string or " \
+ ":numeric filter that picks its predicate from a dropdown"
+ end
+ end
+ end
+
+ # What the two options search in this input's predicate dropdown, if it renders one: a
+ # filter named after a predicate renders the box alone.
+ def dropdown_predicates(input)
+ predicates =
+ case input
+ when ::ActiveAdmin::Inputs::Filters::StringInput then STRING_PREDICATES
+ when ::ActiveAdmin::Inputs::Filters::NumericInput then PREDICATES
+ end
+ predicates unless predicates.nil? || input.seems_searchable?
+ end
+
+ # @return [Hash] :none / :present => its marker, for the options this filter declares
+ def declared_markers(options)
+ declared = PREDICATES.keys.select { |kind| options[kind] }
+ declared.empty? ? {} : ActiveAdminFilterExtensions.markers.slice(*declared)
+ end
+
+ def declared_marker_names(options)
+ declared_markers(options).keys.map { |kind| "#{kind}:" }.join(" and ")
+ end
+
+ def validate_marker_options(attribute, options)
+ declared_markers(options).each_key do |kind|
+ next unless options[kind].is_a?(Hash)
+
+ unknown = options[kind].keys.map(&:to_sym) - %i[label class]
+ next if unknown.empty?
+
+ raise ArgumentError, "filter :#{attribute}: #{kind}: takes true, a label or { label:, class: }, " \
+ "got #{unknown.map(&:inspect).join(', ')}"
+ end
+ end
+
+ def marker_filter_request_value(key)
+ filtering_params.find { |name, _| name.to_s == key }&.last
+ end
+
+ # What the filter declared for one option: `true`, a label, or { label:, class: }.
+ #
+ # @return [Hash] the option's :label, and its :class with the gem's own in front
+ def marker_option(options, kind)
+ declared = options[kind]
+ declared = declared.is_a?(Hash) ? declared.transform_keys(&:to_sym) : { label: declared }
+ label = declared[:label]
+ label = I18n.t(kind, scope: :active_admin_filter_extensions, default: kind.to_s.capitalize) if label.nil? || label == true
+
+ { label: label.to_s, class: [OPTION_CLASS, "filter-extensions-#{kind}", *declared[:class]].join(" ") }
+ end
+
+ # One item of a select: the html attributes ride third, to options_for_select.
+ def marker_option_item(option, kind, value, attributes = {})
+ [option[:label], value, { class: option[:class], OPTION_DATA => kind.to_s }.merge(attributes)]
+ end
+ end
+
+ # The name the None option shipped under, kept for the callers of .search_params and KEY.
+ NoneOption = MarkerOptions
+end
diff --git a/lib/active_admin_filter_extensions/policies.rb b/lib/active_admin_filter_extensions/policies.rb
index 0782ece..09f385f 100644
--- a/lib/active_admin_filter_extensions/policies.rb
+++ b/lib/active_admin_filter_extensions/policies.rb
@@ -314,10 +314,11 @@ def enforce_scalar_policies(q, attribute, options, keys)
end
value = value.reject(&:blank?) if value.is_a?(Array)
+ exempt = policy_exempt_markers(attribute, options, key)
if (sanitizer = options[:sanitize])
sanitizer = Sanitizers.resolve(sanitizer)
- sanitized = sanitize_policed_value(attribute, sanitizer, value)
+ sanitized = sanitize_policed_value(attribute, sanitizer, value, exempt)
value = sanitized
q[key] = value
end
@@ -328,7 +329,7 @@ def enforce_scalar_policies(q, attribute, options, keys)
# Blank input array elements are discarded before searching - ?q[k][]=&q[k][]=draft
# is the shape a multi-select submits - so remove them before sanitizing. Sanitized
# elements are all judged, including ones the sanitizer emptied.
- elements = value.is_a?(Array) ? value : [value]
+ elements = (value.is_a?(Array) ? value : [value]) - exempt
message = elements.lazy
.filter_map { |element| ::MethodOrProcHelper.render_in_context(self, validator, element) }.first
# nil AND false mean "valid" - `condition && "message"` is how Ruby writes these.
@@ -341,6 +342,17 @@ def enforce_scalar_policies(q, attribute, options, keys)
end
end
+ # A None or Present option's marker is the gem's own, not a value the admin typed, so no
+ # value policy is handed it - under the declaring filter's own key only, where the search
+ # rewrites it. Anywhere else it is a value like any other, and a way past the policy if
+ # exempted.
+ def policy_exempt_markers(attribute, options, key)
+ markers = declared_markers(options)
+ return [] if markers.empty? || marker_filter_keys[attribute.to_sym] != key.to_s
+
+ markers.values
+ end
+
# A String, or an Array of Strings - what a multi-valued input submits.
def policed_value_shape?(value)
value.is_a?(String) || (value.is_a?(Array) && value.all?(String))
@@ -349,8 +361,9 @@ def policed_value_shape?(value)
# Element-wise for an Array, so a multi-valued filter is sanitized the way it is
# submitted. On dup'd copies: a sanitizer that mutates in place and returns the same
# object would otherwise be compared against itself and wave its loop through.
- def sanitize_policed_value(attribute, sanitizer, value)
- return value.map { |element| sanitize_policed_value(attribute, sanitizer, element) } if value.is_a?(Array)
+ def sanitize_policed_value(attribute, sanitizer, value, exempt = [])
+ return value.map { |element| sanitize_policed_value(attribute, sanitizer, element, exempt) } if value.is_a?(Array)
+ return value if exempt.include?(value)
sanitized = ::MethodOrProcHelper.render_in_context(self, sanitizer, value.dup).to_s
# The sanitized value lands in the URL and comes back for another pass - a sanitizer
diff --git a/lib/active_admin_filter_extensions/search_keys.rb b/lib/active_admin_filter_extensions/search_keys.rb
index 0659992..ef537d5 100644
--- a/lib/active_admin_filter_extensions/search_keys.rb
+++ b/lib/active_admin_filter_extensions/search_keys.rb
@@ -37,8 +37,7 @@ def filter_search_keys(attribute, options)
raise_filter_default_error(attribute, "could not work out which search key it submits (#{e.class}: #{e.message}) - name the predicate with a Hash instead")
end
- def build_filter_input(attribute, options)
- builder = filter_input_builder
+ def build_filter_input(attribute, options, builder = filter_input_builder)
options = filter_input_options(options, builder)
as = options[:as] || builder.send(:default_input_type, attribute)
builder.send(:namespaced_input_class, as)
diff --git a/spec/integration/empty_values_spec.rb b/spec/integration/empty_values_spec.rb
new file mode 100644
index 0000000..ff51b82
--- /dev/null
+++ b/spec/integration/empty_values_spec.rb
@@ -0,0 +1,56 @@
+# frozen_string_literal: true
+
+require "rails_helper"
+
+# Which of "john", "", " " and NULL each None and Present returns on a string column. A select
+# searches _null and _not_null, the predicate dropdown _blank and _present. The README's table
+# says the same.
+RSpec.describe "None and Present over empty strings", type: :feature do
+ before do
+ { "john" => "john body", "" => "empty body", " " => "space body", nil => "null body" }
+ .each { |title, body| Post.create!(title: title, body: body) }
+ end
+
+ def expect_bodies(*shown)
+ all = ["john body", "empty body", "space body", "null body"]
+ shown.each { |body| expect(page).to have_content(body) }
+ (all - shown).each { |body| expect(page).to have_no_content(body) }
+ end
+
+ describe "on a select" do
+ it "finds only NULL with None" do
+ visit "/admin/select_title_posts?q%5Btitle_eq%5D=__none__"
+
+ expect_bodies("null body")
+ end
+
+ it "finds every other row with Present" do
+ visit "/admin/select_title_posts?q%5Btitle_eq%5D=__present__"
+
+ expect_bodies("john body", "empty body", "space body")
+ end
+ end
+
+ describe "in the predicate dropdown" do
+ it "finds NULL and the empty string with None" do
+ visit "/admin/predicate_posts?q%5Btitle_blank%5D=1"
+
+ expect_bodies("empty body", "null body")
+ end
+
+ it "finds a name and the spaces with Present" do
+ visit "/admin/predicate_posts?q%5Btitle_present%5D=1"
+
+ expect_bodies("john body", "space body")
+ end
+ end
+
+ it "imposes a None predicate default without judging it by validate: or sanitize:" do
+ visit "/admin/default_predicate_posts"
+
+ expect(Rack::Utils.parse_nested_query(URI.parse(page.current_url).query.to_s)["q"])
+ .to eq("title_blank" => "1")
+ expect(page).to have_no_content("Title filter is too short.")
+ expect_bodies("empty body", "null body")
+ end
+end
diff --git a/spec/integration/none_option_spec.rb b/spec/integration/none_option_spec.rb
new file mode 100644
index 0000000..75e752b
--- /dev/null
+++ b/spec/integration/none_option_spec.rb
@@ -0,0 +1,173 @@
+# frozen_string_literal: true
+
+require "rails_helper"
+require "rack/utils"
+
+# `none:` gives a select filter an option for the records whose attribute is empty - the one
+# question no value of its collection can ask. The select submits a sentinel under its own key,
+# and only the search is handed the `_null` condition it stands for.
+RSpec.describe "the None option", type: :feature do
+ let(:none) { ActiveAdminFilterExtensions.none_value }
+ let(:aa_v4) { ActiveAdminFilterExtensions.aa_v4? }
+ let!(:acme) { Account.create!(name: "Acme") }
+ let!(:zenith) { Account.create!(name: "Zenith") }
+
+ before do
+ Post.create!(title: "acme post", status: "published", position: 20, account: acme)
+ Post.create!(title: "zenith post", status: "draft", position: 1, account: zenith)
+ Post.create!(title: "orphan post")
+ end
+
+ def query_of(url)
+ Rack::Utils.parse_nested_query(URI.parse(url).query.to_s)
+ end
+
+ def options_of(name)
+ page.all("select[name='#{name}'] option").map { |option| [option.text, option.value] }
+ end
+
+ # The entry of one search key in the Current Filters panel, which both moved and changed its
+ # hook in Active Admin 4.
+ def current_filter(key)
+ if aa_v4
+ "#active_search_sidebar_section li[data-filter='#{key}']"
+ else
+ "#search_status_sidebar_section li.current_filter_#{key}"
+ end
+ end
+
+ it "renders first, after the blank option" do
+ visit "/admin/none_posts"
+
+ expect(options_of("q[account_id_eq]"))
+ .to eq([["Any", ""], ["None", none], ["Acme", acme.id.to_s], ["Zenith", zenith.id.to_s]])
+ end
+
+ it "heads a multiple select, under the label the filter gave it" do
+ visit "/admin/none_posts"
+
+ expect(options_of("q[status_in][]"))
+ .to eq([["No status", none], %w[draft draft], %w[published published]])
+ end
+
+ it "lists only the records with the attribute empty" do
+ visit "/admin/none_posts"
+ select "None", from: "q[account_id_eq]"
+ click_button "Filter"
+
+ expect(page).to have_content("orphan post")
+ expect(page).to have_no_content("acme post")
+ expect(page).to have_no_content("zenith post")
+ end
+
+ it "stays selected after the submit, under the key the select submitted" do
+ # Ransack is handed account_id_null, so neither the search object nor a rewritten URL could
+ # say which option was picked - the request, left as submitted, does.
+ visit "/admin/none_posts"
+ select "None", from: "q[account_id_eq]"
+ click_button "Filter"
+
+ expect(query_of(page.current_url)["q"]).to include("account_id_eq" => none)
+ expect(page).to have_select("q[account_id_eq]", selected: "None")
+ end
+
+ it "returns the union for None beside a value on a multiple select" do
+ visit "/admin/none_posts"
+ select "No status", from: "q[status_in][]"
+ select "draft", from: "q[status_in][]"
+ click_button "Filter"
+
+ expect(page).to have_content("orphan post")
+ expect(page).to have_content("zenith post")
+ expect(page).to have_no_content("acme post")
+ expect(page).to have_select("q[status_in][]", selected: ["No status", "draft"])
+ end
+
+ it "searches None alone on a multiple select" do
+ visit "/admin/none_posts?q%5Bstatus_in%5D%5B%5D=#{none}"
+
+ expect(page).to have_content("orphan post")
+ expect(page).to have_no_content("zenith post")
+ expect(page).to have_select("q[status_in][]", selected: ["No status"])
+ end
+
+ it "filters the formats the redirect never touches" do
+ visit "/admin/none_posts.csv?q%5Baccount_id_eq%5D=#{none}"
+
+ expect(page).to have_content("orphan post")
+ expect(page).to have_no_content("acme post")
+ end
+
+ it "raises for a filter that is not a select" do
+ expect { visit "/admin/banana_none_posts" }
+ .to raise_error(ArgumentError, /:title_cont declares none:.*needs a select that submits _eq or _in/m)
+ end
+
+ it "answers a required: filter" do
+ # Left unanswered, the filter imposes its default beside the title...
+ visit "/admin/required_none_posts?q%5Btitle_cont%5D=post"
+
+ expect(query_of(page.current_url)["q"])
+ .to eq("title_cont" => "post", "account_id_eq" => acme.id.to_s)
+
+ # ...and "without an account" is an answer, not an absence to fill in.
+ visit "/admin/required_none_posts?q%5Btitle_cont%5D=post&q%5Baccount_id_eq%5D=#{none}"
+
+ expect(query_of(page.current_url)["q"]).to eq("title_cont" => "post", "account_id_eq" => none)
+ expect(page).to have_content("orphan post")
+ expect(page).to have_no_content("acme post")
+ end
+
+ it "can be the filter's default" do
+ visit "/admin/default_none_posts"
+
+ expect(query_of(page.current_url)["q"]).to eq("account_id_eq" => none)
+ expect(page).to have_content("orphan post")
+ expect(page).to have_no_content("acme post")
+ expect(page).to have_select("q[account_id_eq]", selected: "None")
+ end
+
+ describe "beside value policies" do
+ it "is not handed to validate:" do
+ # :integer would refuse the sentinel and reset the filter to the whole table.
+ visit "/admin/policed_none_posts?q%5Baccount_id_eq%5D=#{none}"
+
+ expect(page).to have_no_content("Account filter has an invalid value.")
+ expect(page).to have_content("orphan post")
+ expect(page).to have_no_content("acme post")
+ end
+
+ it "is not handed to sanitize:, while the values beside it are" do
+ # :digits would empty the sentinel; the URL keeps it and carries the cleaned value.
+ visit "/admin/policed_none_posts?q%5Bposition_in%5D%5B%5D=#{none}&q%5Bposition_in%5D%5B%5D=2x0"
+
+ expect(query_of(page.current_url)["q"]).to eq("position_in" => [none, "20"])
+ expect(page).to have_content("orphan post")
+ expect(page).to have_content("acme post")
+ expect(page).to have_no_content("zenith post")
+ end
+
+ it "leaves every other value to the policy" do
+ visit "/admin/policed_none_posts?q%5Baccount_id_eq%5D=abc"
+
+ expect(page).to have_content("Account filter has an invalid value.")
+ end
+ end
+
+ describe "in the Current Filters panel" do
+ it "reads as the option, not as the condition it became" do
+ # Left to Active Admin the `_null` condition reads "Account is null 1".
+ visit "/admin/none_posts?q%5Baccount_id_eq%5D=#{none}"
+
+ expect(page).to have_css(current_filter("account_id_null"), text: /Account equals\s*None/)
+ end
+
+ it "lists None beside the values chosen with it" do
+ # Those sit in an OR grouping, which the panel does not list: left to Active Admin it
+ # says nothing is filtered.
+ visit "/admin/none_posts?q%5Bstatus_in%5D%5B%5D=#{none}&q%5Bstatus_in%5D%5B%5D=draft"
+
+ expect(page).to have_css(current_filter("status_in"), text: /Status in\s*No status and draft/)
+ end
+ end
+end
diff --git a/spec/integration/predicate_option_spec.rb b/spec/integration/predicate_option_spec.rb
new file mode 100644
index 0000000..c836435
--- /dev/null
+++ b/spec/integration/predicate_option_spec.rb
@@ -0,0 +1,279 @@
+# frozen_string_literal: true
+
+require "rails_helper"
+require "rack/utils"
+
+# On a :string or :numeric filter that picks its predicate from a dropdown, `none:` and
+# `present:` are two more predicates in it. They are Ransack's own - `_blank` and `_present` for
+# a string, `_null` and `_not_null` for a number - and have nothing to type, so the gem's script
+# fills and hides the box Active Admin would not submit empty.
+RSpec.describe "the None and Present predicates", type: :feature do
+ let(:aa_v4) { ActiveAdminFilterExtensions.aa_v4? }
+
+ before do
+ Post.create!(title: "titled", body: "titled body", position: 5)
+ Post.create!(title: "", body: "empty title body")
+ Post.create!(title: nil, body: "missing title body")
+ end
+
+ def query_of(url)
+ Rack::Utils.parse_nested_query(URI.parse(url).query.to_s)
+ end
+
+ def predicates_of(attribute)
+ page.find("#q_#{attribute}_input select")
+ end
+
+ def box_of(attribute)
+ page.find("#q_#{attribute}_input input", visible: :all)
+ end
+
+ # The entry of one search key in the Current Filters panel, which both moved and changed its
+ # hook in Active Admin 4.
+ def current_filter(key)
+ if aa_v4
+ "#active_search_sidebar_section li[data-filter='#{key}']"
+ else
+ "#search_status_sidebar_section li.current_filter_#{key}"
+ end
+ end
+
+ describe "in the dropdown" do
+ before { visit "/admin/predicate_posts" }
+
+ it "close the list of a :string filter, as _blank and _present" do
+ options = predicates_of(:title).all("option").map { |option| [option.text, option.value] }
+
+ expect(options.first).to eq(%w[Contains title_cont])
+ expect(options.last(2)).to eq([%w[None title_blank], ["Any title", "title_present"]])
+ end
+
+ it "close the list of a :numeric filter, as _null and _not_null" do
+ options = predicates_of(:position).all("option").map { |option| [option.text, option.value] }
+
+ expect(options.first).to eq(%w[Equals position_eq])
+ expect(options.last(2)).to eq([["No position", "position_null"], %w[Present position_not_null]])
+ end
+
+ it "carry the hooks the select options carry" do
+ none = predicates_of(:title).find("option[value='title_blank']")
+ present = predicates_of(:title).find("option[value='title_present']")
+
+ expect(none[:class]).to eq("filter-extensions-option filter-extensions-none")
+ expect(none["data-filter-extensions-option"]).to eq("none")
+ expect(present[:class]).to eq("filter-extensions-option filter-extensions-present font-bold")
+ expect(present["data-filter-extensions-option"]).to eq("present")
+ expect(predicates_of(:title).find("option[value='title_cont']")[:class]).to be_blank
+ end
+ end
+
+ describe "in the search" do
+ it "lists the records with no title, an empty one included" do
+ visit "/admin/predicate_posts?q%5Btitle_blank%5D=1"
+
+ expect(page).to have_content("empty title body")
+ expect(page).to have_content("missing title body")
+ expect(page).to have_no_content("titled body")
+ end
+
+ it "lists the records with a title" do
+ visit "/admin/predicate_posts?q%5Btitle_present%5D=1"
+
+ expect(page).to have_content("titled body")
+ expect(page).to have_no_content("empty title body")
+ expect(page).to have_no_content("missing title body")
+ end
+
+ it "lists the records with no number, and the ones with one" do
+ visit "/admin/predicate_posts?q%5Bposition_null%5D=1"
+
+ expect(page).to have_content("empty title body")
+ expect(page).to have_no_content("titled body")
+
+ visit "/admin/predicate_posts?q%5Bposition_not_null%5D=1"
+
+ expect(page).to have_content("titled body")
+ expect(page).to have_no_content("empty title body")
+ end
+ end
+
+ it "is restored as the chosen predicate, the box holding what was submitted" do
+ visit "/admin/predicate_posts?q%5Btitle_blank%5D=1&q%5Bposition_not_null%5D=1"
+
+ expect(predicates_of(:title).value).to eq("title_blank")
+ expect(box_of(:title)[:name]).to eq("q[title_blank]")
+ expect(box_of(:title).value).to eq("1")
+ expect(predicates_of(:position).value).to eq("position_not_null")
+ expect(box_of(:position)[:name]).to eq("q[position_not_null]")
+ expect(box_of(:position).value).to eq("1")
+ end
+
+ describe "in the Current Filters panel" do
+ it "reads as the option, not as the predicate" do
+ # Left to Active Admin the condition reads "Title is blank true".
+ visit "/admin/predicate_posts?q%5Btitle_blank%5D=1&q%5Bposition_not_null%5D=1"
+
+ expect(page).to have_css(current_filter("title_blank"), text: /Title equals\s*None/)
+ expect(page).to have_css(current_filter("position_not_null"), text: /Position equals\s*Present/)
+ end
+
+ it "reads under the label the filter gave the option" do
+ visit "/admin/predicate_posts?q%5Btitle_present%5D=1&q%5Bposition_null%5D=1"
+
+ expect(page).to have_css(current_filter("title_present"), text: /Title equals\s*Any title/)
+ expect(page).to have_css(current_filter("position_null"), text: /Position equals\s*No position/)
+ end
+ end
+
+ describe "beside the filter's other extensions" do
+ it "answers required:, and is not handed to validate:" do
+ # Unanswered, the filter imposes its default...
+ visit "/admin/policed_predicate_posts"
+
+ expect(query_of(page.current_url)["q"]).to eq("title_cont" => "acme")
+
+ # ...and "1" is the predicate's answer, not a title too short to search.
+ visit "/admin/policed_predicate_posts?q%5Btitle_blank%5D=1"
+
+ expect(query_of(page.current_url)["q"]).to eq("title_blank" => "1")
+ expect(page).to have_no_content("Title filter is too short.")
+ expect(page).to have_content("empty title body")
+ expect(page).to have_no_content("titled body")
+ end
+ end
+
+ it "raises for a :string filter named after a predicate" do
+ expect { visit "/admin/banana_none_posts" }
+ .to raise_error(ArgumentError, /:title_cont declares none:.*picks its predicate from a dropdown/m)
+ end
+
+ # Active Admin's own script renames the box after the chosen predicate and leaves every empty
+ # field out of the submit. The gem's script is what makes a predicate with nothing to type
+ # reach the server.
+ describe "with the gem's script", :js do
+ def choose_predicate(attribute, text)
+ predicates_of(attribute).select(text)
+ end
+
+ it "submits None from a :string filter with nothing typed" do
+ visit "/admin/predicate_posts"
+ choose_predicate(:title, "None")
+
+ expect(page).to have_css("#q_title_input input", visible: :hidden)
+
+ click_button "Filter"
+
+ expect(page).to have_css(current_filter("title_blank"), text: /Title equals\s*None/)
+ expect(query_of(page.current_url)["q"]).to eq("title_blank" => "1")
+ expect(page).to have_content("empty title body")
+ expect(page).to have_content("missing title body")
+ expect(page).to have_no_content("titled body")
+ expect(predicates_of(:title).value).to eq("title_blank")
+ expect(page).to have_css("#q_title_input input", visible: :hidden)
+ end
+
+ it "submits Present from a :string filter, over what was typed" do
+ visit "/admin/predicate_posts"
+ box_of(:title).set("missing")
+ choose_predicate(:title, "Any title")
+ click_button "Filter"
+
+ expect(page).to have_css(current_filter("title_present"), text: /Title equals\s*Any title/)
+ expect(query_of(page.current_url)["q"]).to eq("title_present" => "1")
+ expect(page).to have_content("titled body")
+ expect(page).to have_no_content("missing title body")
+ expect(predicates_of(:title).value).to eq("title_present")
+ expect(page).to have_css("#q_title_input input", visible: :hidden)
+ end
+
+ it "submits None and Present from a :numeric filter" do
+ visit "/admin/predicate_posts"
+ choose_predicate(:position, "No position")
+ click_button "Filter"
+
+ expect(page).to have_css(current_filter("position_null"), text: /Position equals\s*No position/)
+ expect(query_of(page.current_url)["q"]).to eq("position_null" => "1")
+ expect(page).to have_content("empty title body")
+ expect(page).to have_no_content("titled body")
+ expect(page).to have_css("#q_position_input input", visible: :hidden)
+
+ choose_predicate(:position, "Present")
+ click_button "Filter"
+
+ expect(page).to have_css(current_filter("position_not_null"), text: /Position equals\s*Present/)
+ expect(query_of(page.current_url)["q"]).to eq("position_not_null" => "1")
+ expect(page).to have_content("titled body")
+ expect(page).to have_no_content("empty title body")
+ expect(predicates_of(:position).value).to eq("position_not_null")
+ expect(page).to have_css("#q_position_input input", visible: :hidden)
+ end
+
+ # A browser that restores the form on Back sets the select and fires no change event.
+ it "names the box after a predicate set without a change event" do
+ visit "/admin/predicate_posts?q%5Btitle_cont%5D=x"
+ page.execute_script(<<~JS)
+ var select = document.querySelector("#q_title_input select");
+ select.value = "title_blank";
+ window.ActiveAdminFilterExtensions.sync(document);
+ JS
+ click_button "Filter"
+
+ expect(query_of(page.current_url)["q"]).to eq("title_blank" => "1")
+ end
+
+ # Active Admin 3 does not restore a false answer, so it is dropped; neither version may
+ # turn it into the opposite search.
+ it "never turns a false answer into 1" do
+ visit "/admin/predicate_posts?q%5Btitle_blank%5D=0"
+ click_button "Filter"
+
+ expect(query_of(page.current_url).dig("q", "title_blank")).not_to eq("1")
+ end
+
+ it "answers a predicate picked over a false answer with 1" do
+ visit "/admin/predicate_posts?q%5Btitle_blank%5D=0"
+ choose_predicate(:title, "Any title")
+ choose_predicate(:title, "None")
+ click_button "Filter"
+
+ expect(query_of(page.current_url)["q"]).to eq("title_blank" => "1")
+ end
+
+ it "keeps a restored predicate through the next submit" do
+ visit "/admin/predicate_posts?q%5Btitle_blank%5D=1"
+ choose_predicate(:position, "Present")
+ click_button "Filter"
+
+ expect(page).to have_css(current_filter("position_not_null"))
+ expect(query_of(page.current_url)["q"]).to eq("title_blank" => "1", "position_not_null" => "1")
+ end
+
+ it "gives the box back, empty, with any other predicate" do
+ visit "/admin/predicate_posts?q%5Btitle_blank%5D=1"
+
+ expect(page).to have_css("#q_title_input input", visible: :hidden)
+
+ choose_predicate(:title, "Contains")
+
+ expect(page).to have_css("#q_title_input input[name='q[title_cont]']", visible: :visible)
+ expect(box_of(:title).value).to eq("")
+
+ box_of(:title).set("titled")
+ click_button "Filter"
+
+ expect(page).to have_css(current_filter("title_cont"))
+ expect(query_of(page.current_url)["q"]).to eq("title_cont" => "titled")
+ expect(page).to have_content("titled body")
+ expect(page).to have_no_content("empty title body")
+ end
+
+ it "leaves the box alone between Active Admin's own predicates" do
+ visit "/admin/predicate_posts"
+ box_of(:title).set("titled")
+ choose_predicate(:title, "Equals")
+
+ expect(page).to have_css("#q_title_input input[name='q[title_eq]']", visible: :visible)
+ expect(box_of(:title).value).to eq("titled")
+ end
+ end
+end
diff --git a/spec/integration/present_option_spec.rb b/spec/integration/present_option_spec.rb
new file mode 100644
index 0000000..6934af2
--- /dev/null
+++ b/spec/integration/present_option_spec.rb
@@ -0,0 +1,210 @@
+# frozen_string_literal: true
+
+require "rails_helper"
+require "rack/utils"
+
+# `present:` is the None option's opposite: a select filter's option for the records whose
+# attribute holds anything at all. It submits a marker of its own, and only the search is
+# handed the `_not_null` condition it stands for.
+RSpec.describe "the Present option", type: :feature do
+ let(:none) { ActiveAdminFilterExtensions.none_value }
+ let(:present) { ActiveAdminFilterExtensions.present_value }
+ let(:aa_v4) { ActiveAdminFilterExtensions.aa_v4? }
+ let!(:acme) { Account.create!(name: "Acme") }
+ let!(:zenith) { Account.create!(name: "Zenith") }
+
+ before do
+ Post.create!(title: "acme post", status: "published", position: 20, account: acme)
+ Post.create!(title: "zenith post", status: "draft", position: 1, account: zenith)
+ Post.create!(title: "orphan post")
+ end
+
+ def query_of(url)
+ Rack::Utils.parse_nested_query(URI.parse(url).query.to_s)
+ end
+
+ def options_of(name)
+ page.all("select[name='#{name}'] option").map { |option| [option.text, option.value] }
+ end
+
+ def option_of(name, value)
+ page.find("select[name='#{name}'] option[value='#{value}']")
+ end
+
+ # The entry of one search key in the Current Filters panel, which both moved and changed its
+ # hook in Active Admin 4.
+ def current_filter(key)
+ if aa_v4
+ "#active_search_sidebar_section li[data-filter='#{key}']"
+ else
+ "#search_status_sidebar_section li.current_filter_#{key}"
+ end
+ end
+
+ it "is listed with the marker it submits" do
+ expect(ActiveAdminFilterExtensions.markers).to eq(none: "__none__", present: "__present__")
+ end
+
+ it "renders right after the None option" do
+ visit "/admin/present_posts"
+
+ expect(options_of("q[account_id_eq]"))
+ .to eq([["Any", ""], ["No account", none], ["Present", present],
+ ["Acme", acme.id.to_s], ["Zenith", zenith.id.to_s]])
+ expect(options_of("q[status_in][]"))
+ .to eq([["None", none], ["Any status", present], %w[draft draft], %w[published published]])
+ end
+
+ it "renders right after the blank option on a filter with no None" do
+ visit "/admin/present_posts"
+
+ expect(options_of("q[position_eq]")).to eq([["Any", ""], ["Present", present], %w[1 1], %w[20 20]])
+ end
+
+ describe "the option's hooks for the application's CSS" do
+ before { visit "/admin/present_posts" }
+
+ it "carries the gem's classes and names its kind" do
+ option = option_of("q[account_id_eq]", present)
+
+ expect(option[:class]).to eq("filter-extensions-option filter-extensions-present")
+ expect(option["data-filter-extensions-option"]).to eq("present")
+ expect(option_of("q[status_in][]", none)[:class]).to eq("filter-extensions-option filter-extensions-none")
+ expect(option_of("q[status_in][]", none)["data-filter-extensions-option"]).to eq("none")
+ end
+
+ it "appends the classes of the Hash form" do
+ expect(option_of("q[account_id_eq]", none)[:class])
+ .to eq("filter-extensions-option filter-extensions-none text-red-700 italic")
+ expect(option_of("q[position_eq]", present)[:class])
+ .to eq("filter-extensions-option filter-extensions-present font-bold")
+ end
+
+ it "leaves the collection's own options bare" do
+ option = option_of("q[account_id_eq]", acme.id)
+
+ expect(option[:class]).to be_blank
+ expect(option["data-filter-extensions-option"]).to be_nil
+ end
+ end
+
+ it "lists only the records with the attribute filled in" do
+ visit "/admin/present_posts"
+ select "Present", from: "q[account_id_eq]"
+ click_button "Filter"
+
+ expect(page).to have_content("acme post")
+ expect(page).to have_content("zenith post")
+ expect(page).to have_no_content("orphan post")
+ end
+
+ it "stays selected after the submit, under the key the select submitted" do
+ visit "/admin/present_posts"
+ select "Present", from: "q[account_id_eq]"
+ click_button "Filter"
+
+ expect(query_of(page.current_url)["q"]).to include("account_id_eq" => present)
+ expect(page).to have_select("q[account_id_eq]", selected: "Present")
+ end
+
+ it "searches Present alone on a multiple select" do
+ visit "/admin/present_posts?q%5Bstatus_in%5D%5B%5D=#{present}"
+
+ expect(page).to have_content("acme post")
+ expect(page).to have_content("zenith post")
+ expect(page).to have_no_content("orphan post")
+ expect(page).to have_select("q[status_in][]", selected: ["Any status"])
+ end
+
+ it "takes in the values chosen beside it on a multiple select" do
+ # Every draft has a status, so "any status, or draft" is "any status".
+ visit "/admin/present_posts"
+ select "Any status", from: "q[status_in][]"
+ select "draft", from: "q[status_in][]"
+ click_button "Filter"
+
+ expect(page).to have_content("acme post")
+ expect(page).to have_content("zenith post")
+ expect(page).to have_no_content("orphan post")
+ expect(page).to have_select("q[status_in][]", selected: ["Any status", "draft"])
+ end
+
+ it "asks nothing of the attribute beside None" do
+ # Empty or not is every record, so the two together search no condition at all.
+ visit "/admin/present_posts?q%5Bstatus_in%5D%5B%5D=#{none}&q%5Bstatus_in%5D%5B%5D=#{present}"
+
+ expect(page).to have_content("acme post")
+ expect(page).to have_content("zenith post")
+ expect(page).to have_content("orphan post")
+ expect(page).to have_select("q[status_in][]", selected: ["None", "Any status"])
+ expect(page).to have_no_css(current_filter("status_null"))
+ expect(page).to have_no_css(current_filter("status_not_null"))
+ end
+
+ it "filters the formats the redirect never touches" do
+ visit "/admin/present_posts.csv?q%5Baccount_id_eq%5D=#{present}"
+
+ expect(page).to have_content("acme post")
+ expect(page).to have_no_content("orphan post")
+ end
+
+ it "is a plain value on a filter that declares only None" do
+ # Rewritten only where the filter declared it: here it is searched as an account id.
+ visit "/admin/none_posts?q%5Baccount_id_eq%5D=#{present}"
+
+ expect(page).to have_no_content("acme post")
+ expect(page).to have_no_content("orphan post")
+ end
+
+ it "raises for a filter that is neither a select nor a predicate dropdown" do
+ expect { visit "/admin/banana_present_posts" }
+ .to raise_error(ArgumentError, /:status declares present:.*needs a select that submits _eq or _in/m)
+ end
+
+ it "raises for a Hash form key it does not know" do
+ expect { visit "/admin/banana_marker_hash_posts" }
+ .to raise_error(ArgumentError, /:account: none: takes true, a label or \{ label:, class: \}, got :text/)
+ end
+
+ it "answers a required: filter" do
+ visit "/admin/required_none_posts?q%5Btitle_cont%5D=post&q%5Baccount_id_eq%5D=#{present}"
+
+ expect(query_of(page.current_url)["q"]).to eq("title_cont" => "post", "account_id_eq" => present)
+ expect(page).to have_content("acme post")
+ expect(page).to have_no_content("orphan post")
+ end
+
+ describe "beside value policies" do
+ it "is not handed to validate:" do
+ visit "/admin/policed_none_posts?q%5Baccount_id_eq%5D=#{present}"
+
+ expect(page).to have_no_content("Account filter has an invalid value.")
+ expect(page).to have_content("acme post")
+ expect(page).to have_no_content("orphan post")
+ end
+
+ it "is not handed to sanitize:, while the values beside it are" do
+ visit "/admin/policed_none_posts?q%5Bposition_in%5D%5B%5D=#{present}&q%5Bposition_in%5D%5B%5D=2x0"
+
+ expect(query_of(page.current_url)["q"]).to eq("position_in" => [present, "20"])
+ expect(page).to have_content("acme post")
+ expect(page).to have_content("zenith post")
+ expect(page).to have_no_content("orphan post")
+ end
+ end
+
+ describe "in the Current Filters panel" do
+ it "reads as the option, not as the condition it became" do
+ # Left to Active Admin the `_not_null` condition reads "Account is not null 1".
+ visit "/admin/present_posts?q%5Baccount_id_eq%5D=#{present}"
+
+ expect(page).to have_css(current_filter("account_id_not_null"), text: /Account equals\s*Present/)
+ end
+
+ it "reads as the option alone when values were chosen beside it" do
+ visit "/admin/present_posts?q%5Bstatus_in%5D%5B%5D=#{present}&q%5Bstatus_in%5D%5B%5D=draft"
+
+ expect(page).to have_css(current_filter("status_not_null"), text: /Status equals\s*Any status\z/)
+ end
+ end
+end
diff --git a/spec/marker_options_spec.rb b/spec/marker_options_spec.rb
new file mode 100644
index 0000000..028ae5b
--- /dev/null
+++ b/spec/marker_options_spec.rb
@@ -0,0 +1,48 @@
+# frozen_string_literal: true
+
+require "spec_helper"
+
+# What a caller outside the controller is given: the rewrite of a `q` that carries the markers.
+# A select's options endpoint searches the parent filter's value this way.
+RSpec.describe ActiveAdminFilterExtensions::MarkerOptions do
+ let(:none) { "__none__" }
+ let(:present) { "__present__" }
+
+ it "answers to the name the None option shipped under" do
+ expect(ActiveAdminFilterExtensions::NoneOption).to equal(described_class)
+ expect("account_id_eq").to match(ActiveAdminFilterExtensions::NoneOption::KEY)
+ expect("account_id_not_eq").to_not match(ActiveAdminFilterExtensions::NoneOption::KEY)
+ end
+
+ describe ".search_params" do
+ it "turns the None marker into _null, under the given keys only" do
+ params = { "account_id_eq" => none, "status_eq" => none, "title_cont" => "post" }
+
+ expect(described_class.search_params(params, %w[account_id_eq], none))
+ .to eq("account_id_null" => "1", "status_eq" => none, "title_cont" => "post")
+ end
+
+ it "groups None with the values chosen beside it" do
+ expect(described_class.search_params({ "status_in" => [none, "draft"] }, %w[status_in], none))
+ .to eq("g" => [{ "m" => "or", "status_in" => %w[draft], "status_null" => "1" }])
+ end
+
+ it "leaves the Present marker alone unless it is given" do
+ expect(described_class.search_params({ "account_id_eq" => present }, %w[account_id_eq], none))
+ .to eq("account_id_eq" => present)
+ end
+
+ it "turns the Present marker into _not_null, dropping the values beside it" do
+ params = { "account_id_eq" => present, "status_in" => [present, "draft"] }
+
+ expect(described_class.search_params(params, %w[account_id_eq status_in], none, present))
+ .to eq("account_id_not_null" => "1", "status_not_null" => "1")
+ end
+
+ it "searches no condition for None and Present together" do
+ params = { "status_in" => [none, present, "draft"], "title_cont" => "post" }
+
+ expect(described_class.search_params(params, %w[status_in], none, present)).to eq("title_cont" => "post")
+ end
+ end
+end
diff --git a/spec/spec_helper.rb b/spec/spec_helper.rb
index b5452ad..b1edebb 100644
--- a/spec/spec_helper.rb
+++ b/spec/spec_helper.rb
@@ -11,6 +11,7 @@
require "active_admin_filter_extensions/search_keys"
require "active_admin_filter_extensions/required_filters"
require "active_admin_filter_extensions/filter_defaults"
+require "active_admin_filter_extensions/marker_options"
require "active_admin_filter_extensions/policies"
# `DataAccess` only needs `params`, `active_admin_config` and something that answers `ransack`.
@@ -64,6 +65,7 @@ def filter_ransack_options = {}
include ActiveAdminFilterExtensions::SearchKeys
include ActiveAdminFilterExtensions::RequiredFilters
include ActiveAdminFilterExtensions::FilterDefaults
+ include ActiveAdminFilterExtensions::MarkerOptions
end
RSpec.configure do |config|
diff --git a/spec/support/rails_template.rb b/spec/support/rails_template.rb
index c14552c..c8027cb 100644
--- a/spec/support/rails_template.rb
+++ b/spec/support/rails_template.rb
@@ -7,13 +7,17 @@
File.write("app/assets/config/manifest.js", "//= link_tree ../images\n")
# One column per filter input type, so every input can be exercised against a real index.
+# account_id is a plain nullable column rather than a reference: a post without an account is
+# what the None option filters for, and what the Present option leaves out.
generate :model,
"post title:string body:text status:string position:integer " \
- "published_date:date starred:boolean --force"
+ "published_date:date starred:boolean account_id:integer --force"
+generate :model, "account name:string --force"
inject_into_file "app/models/post.rb",
+ " belongs_to :account, optional: true\n" \
" def self.ransackable_attributes(auth_object = nil)\n" \
- " %w[id title body status position published_date starred]\n" \
+ " %w[id title body status position published_date starred account_id]\n" \
" end\n" \
" def self.ransackable_associations(auth_object = nil)\n" \
" []\n" \
@@ -620,6 +624,92 @@ def filter_defaults_apply?
filter :title
end
+ ActiveAdmin.register Post, as: "NonePost" do
+ # The None option on a single and on a multiple select: a relation behind a Proc with the
+ # shipped label, an Array with the filter's own.
+ filter :account, as: :select, collection: proc { Account.order(:name) }, extensions: { none: true }
+ filter :status, as: :select, multiple: true, collection: %w[draft published],
+ extensions: { none: "No status" }
+ end
+
+ ActiveAdmin.register Post, as: "BananaNonePost" do
+ # A :string filter named after a predicate has no dropdown to add to - the suite proves
+ # that raises.
+ filter :title_cont, as: :string, extensions: { none: true }
+ end
+
+ ActiveAdmin.register Post, as: "PresentPost" do
+ # The Present option: after None on a single and on a multiple select, and on its own.
+ # The Hash form adds the classes the application styles the option with.
+ filter :account, as: :select, collection: proc { Account.order(:name) },
+ extensions: { none: { label: "No account", class: "text-red-700 italic" },
+ present: true }
+ filter :status, as: :select, multiple: true, collection: %w[draft published],
+ extensions: { none: true, present: "Any status" }
+ filter :position, as: :select, collection: [1, 20], extensions: { present: { class: "font-bold" } }
+ end
+
+ ActiveAdmin.register Post, as: "BananaPresentPost" do
+ # Check boxes are neither a select nor a predicate dropdown - the suite proves that raises.
+ filter :status, as: :check_boxes, collection: %w[draft published], extensions: { present: true }
+ end
+
+ ActiveAdmin.register Post, as: "PredicatePost" do
+ # None and Present as predicates, in the dropdown of a :string and of a :numeric filter.
+ filter :title, extensions: { none: true, present: { label: "Any title", class: "font-bold" } }
+ # min: is the host's own: a held box must not fail it.
+ filter :position, as: :numeric, min: 10, extensions: { none: "No position", present: true }
+ end
+
+ ActiveAdmin.register Post, as: "PolicedPredicatePost" do
+ # The None predicate beside the filter's other extensions: it answers required:, and it
+ # is no text for validate: to judge.
+ filter :title, extensions: { none: true, required: true, default: "acme",
+ validate: ->(value) { "Title filter is too short." if value.size < 3 } }
+ end
+
+ ActiveAdmin.register Post, as: "DefaultPredicatePost" do
+ # A None predicate as the default: a submitted title_blank=1 skips validate: and
+ # sanitize:, and so does the default.
+ filter :title, extensions: { none: true, default: { blank: "1" }, sanitize: :digits,
+ validate: ->(value) { "Title filter is too short." if value.size < 3 } }
+ end
+
+ ActiveAdmin.register Post, as: "SelectTitlePost" do
+ # None and Present on a select over a string column, beside the dropdown of PredicatePost.
+ filter :title, as: :select, collection: ["john"], extensions: { none: true, present: true }
+ end
+
+ ActiveAdmin.register Post, as: "BananaMarkerHashPost" do
+ # The Hash form takes label: and class: - anything else is a typo, and raises.
+ filter :account, as: :select, collection: proc { Account.order(:name) },
+ extensions: { none: { text: "No account" } }
+ end
+
+ ActiveAdmin.register Post, as: "RequiredNonePost" do
+ # "Without an account" and "with any account" are answers to a required filter, not its
+ # absence.
+ filter :title_cont, as: :string
+ filter :account, as: :select, collection: proc { Account.order(:name) },
+ extensions: { none: true, present: true, required: true,
+ default: -> { Account.find_by(name: "Acme")&.id } }
+ end
+
+ ActiveAdmin.register Post, as: "DefaultNonePost" do
+ # The sentinel as the default: the index opens on the posts without an account.
+ filter :account, as: :select, collection: proc { Account.order(:name) },
+ extensions: { none: true, default: -> { ActiveAdminFilterExtensions.none_value } }
+ end
+
+ ActiveAdmin.register Post, as: "PolicedNonePost" do
+ # Value policies beside the None and Present options: a marker is not a value the admin
+ # typed, so neither policy is handed it - :digits would empty it, :integer would refuse it.
+ filter :account, as: :select, collection: proc { Account.order(:name) },
+ extensions: { none: true, present: true, validate: :integer }
+ filter :position, as: :select, multiple: true, collection: [1, 20],
+ extensions: { none: true, present: true, sanitize: :digits, validate: :integer }
+ end
+
ActiveAdmin.register Post, as: "CollidingNoticePost" do
# The notice on its DEFAULT flash key - the same :notice a batch action writes. Both have
# to coexist on the redirect: the arriving message wins, it names what just happened.
@@ -645,6 +735,20 @@ def filter_defaults_apply?
end
RUBY
+# The gem's script, the way the README installs it: imported from Active Admin 4's import map
+# in the layout's head, required from Active Admin 3's Sprockets manifest.
+if Gem.loaded_specs["activeadmin"].version >= Gem::Version.new("4.0.0.beta1")
+ html_head = File.join(Gem.loaded_specs["activeadmin"].full_gem_path,
+ "app/views/active_admin/_html_head.html.erb")
+ file "app/views/active_admin/_html_head.html.erb", File.read(html_head) + <<~ERB
+ <%= javascript_import_module_tag "active_admin_filter_extensions" %>
+ ERB
+else
+ inject_into_file "app/assets/javascripts/active_admin.js",
+ "\n//= require active_admin_filter_extensions",
+ after: "//= require active_admin/base"
+end
+
# Active Admin 4's flash partial renders only :error, :alert and :notice, with no class per key.
# An app that moves the notice to a key of its own renders that key itself, as this one does.
if Gem.loaded_specs["activeadmin"].version >= Gem::Version.new("4.0.0.beta1")