Class: RESTFramework::Filters::SearchFilter

Inherits:
BaseFilter
  • Object
show all
Defined in:
lib/rest_framework/filters/search_filter.rb

Instance Method Summary collapse

Methods inherited from BaseFilter

#initialize

Constructor Details

This class inherits a constructor from RESTFramework::Filters::BaseFilter

Instance Method Details

#_get_fieldsObject

Get a list of search fields for the current action.



3
4
5
6
7
8
9
10
11
12
# File 'lib/rest_framework/filters/search_filter.rb', line 3

def _get_fields
  if search_fields = @controller.search_fields
    return search_fields&.map(&:to_s)
  end

  columns = @controller.class.get_model.column_names
  return @controller.get_fields.select { |f|
    f.in?(RESTFramework.config.search_columns) && f.in?(columns)
  }
end

#filter_data(data) ⇒ Object

Filter data according to the request query parameters.



15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
# File 'lib/rest_framework/filters/search_filter.rb', line 15

def filter_data(data)
  search = @controller.request.query_parameters[@controller.search_query_param]

  if search.present?
    if fields = self._get_fields.presence
      # MySQL doesn't support casting to VARCHAR, so we need to use CHAR instead.
      data_type = if data.connection.adapter_name =~ /mysql/i
        "CHAR"
      else
        # Sufficient for both PostgreSQL and SQLite.
        "VARCHAR"
      end

      # Ensure we pass user input as arguments to prevent SQL injection.
      return data.where(
        fields.map { |f|
          "CAST(#{f} AS #{data_type}) #{@controller.search_ilike ? "ILIKE" : "LIKE"} ?"
        }.join(" OR "),
        *(["%#{search}%"] * fields.length),
      )
    end
  end

  return data
end