55module AdministrateRansack
66 module Searchable
77 def scoped_resource
8- options = respond_to? ( :ransack_options ) ? ransack_options : { }
9- begin
10- @ransack_results = super . ransack ( params [ :q ] , **options )
11- rescue ArgumentError => e
12- handle_ransack_argument_error ( e )
13- set_flash_message_as_ransack_argument_error ( e )
14- @ransack_results = reset_ransack_result_on_error ( super ) . ransack ( { } , **options )
15- end
16- @ransack_results . result ( distinct : true )
8+ options = respond_to? ( :ransack_options , true ) ? ransack_options : { }
9+ distinct = respond_to? ( :ransack_result_distinct , true ) ? ransack_result_distinct : true
10+ @ransack_results = prepare_search ( resource_collection : super , query_params : params [ :q ] , options : options )
11+ @ransack_results . result ( distinct : distinct )
1712 end
1813
1914 # ref => https://github.com/thoughtbot/administrate/blob/v0.18.0/app/helpers/administrate/application_helper.rb#L72-L78
@@ -33,29 +28,27 @@ def prepended(base)
3328
3429 private
3530
36- def set_flash_message_as_ransack_argument_error ( error )
37- if error . message . eql? ( "Invalid sorting parameter provided" )
38- flash . now [ :alert ] = I18n . t (
39- :invalid_sorting_parameter_provided ,
40- scope : [ :administrate_ransack , :errors ] ,
41- default : error . message
42- )
43- elsif error . message . start_with? ( "Invalid search term " )
44- flash . now [ :alert ] = I18n . t (
45- :invalid_search_term ,
46- search_term : error . message . split ( ' ' ) [ 3 ..] . join ( ' ' ) ,
47- scope : [ :administrate_ransack , :errors ] ,
48- default : error . message
49- )
31+ def prepare_search ( resource_collection :, query_params :, options :)
32+ resource_collection . ransack ( query_params , **options )
33+ rescue ArgumentError => e
34+ if defined? ( Ransack ::InvalidSearchError ) && e . is_a? ( Ransack ::InvalidSearchError ) # rubocop:disable Style/GuardClause
35+ ransack_invalid_search_error ( e )
36+ resource_collection . ransack ( { } , **options )
37+ else
38+ raise e
5039 end
5140 end
5241
53- def handle_ransack_argument_error ( error )
54- super if defined? ( super )
42+ def ransack_invalid_search_error ( error )
43+ if respond_to? ( :invalid_search_callback , true )
44+ invalid_search_callback ( error )
45+ else
46+ invalid_search_flash_message ( error , severity : :alert )
47+ end
5548 end
5649
57- def reset_ransack_result_on_error ( super_scoped_resource )
58- super_scoped_resource . none
50+ def invalid_search_flash_message ( error , severity : )
51+ flash . now [ severity ] = I18n . t ( 'administrate_ransack.errors.invalid_search' , default : error . message )
5952 end
6053 end
6154end
0 commit comments