Implement ransackable whitelisting

This commit is contained in:
Matt-Yorkley
2021-09-02 11:01:05 +01:00
parent fd8de65749
commit b25759670e
2 changed files with 54 additions and 0 deletions

View File

@@ -4,6 +4,7 @@ class ApplicationRecord < ActiveRecord::Base
include DelegateBelongsTo
include Spree::Core::Permalinks
include Spree::Preferences::Preferable
include Searchable
self.abstract_class = true
end

View File

@@ -0,0 +1,53 @@
# frozen_string_literal: true
# Whitelists model attributes, scopes, and associations that can be searched on with Ransack.
# Exposes methods for defining the whitelists, eg:
#
# class Widget < ApplicationRecord
# searchable_attributes :number, :state
# searchable_scopes :activated, :disabled
#
# ...
# end
module Searchable
extend ActiveSupport::Concern
DEFAULT_SEARCHABLE_ATTRIBUTES = [
:id, :name, :description, :created_at, :updated_at, :completed_at, :deleted_at
].freeze
included do
class_attribute :whitelisted_search_attributes, instance_accessor: false, default: []
class_attribute :whitelisted_search_associations, instance_accessor: false, default: []
class_attribute :whitelisted_search_scopes, instance_accessor: false, default: []
end
class_methods do
def ransackable_associations(*_args)
self.whitelisted_search_associations.map(&:to_s)
end
def ransackable_attributes(*_args)
(DEFAULT_SEARCHABLE_ATTRIBUTES | self.whitelisted_search_attributes).map(&:to_s)
end
def ransackable_scopes(*_args)
self.whitelisted_search_scopes.map(&:to_s)
end
private
def searchable_attributes(*attrs)
self.whitelisted_search_attributes = attrs
end
def searchable_associations(*attrs)
self.whitelisted_search_associations = attrs
end
def searchable_scopes(*attrs)
self.whitelisted_search_scopes = attrs
end
end
end