Module: JSONAPI::Utils::Support::Filter::Default

Included in:
Response::Support
Defined in:
lib/jsonapi/utils/support/filter/default.rb

Instance Method Summary collapse

Instance Method Details

#apply_filter(records, options = {}) ⇒ ActiveRecord::Relation, Array

Apply default equality filters.

e.g.: User.where(name: 'Foobar')

Parameters:

  • records (ActiveRecord::Relation, Array)

    collection of records e.g.: User.all or [{ id: 1, name: ‘Tiago’ }, { id: 2, name: ‘Doug’ }]

  • options (Hash) (defaults to: {})

    JU’s options e.g.: { filter: false, paginate: false }

Returns:

  • (ActiveRecord::Relation, Array)


15
16
17
18
19
20
21
# File 'lib/jsonapi/utils/support/filter/default.rb', line 15

def apply_filter(records, options = {})
  if apply_filter?(records, options)
    records.where(filter_params)
  else
    records
  end
end

#apply_filter?(records, options = {}) ⇒ Boolean

Check whether default filters should be applied.

Parameters:

  • records (ActiveRecord::Relation, Array)

    collection of records e.g.: User.all or [{ id: 1, name: ‘Tiago’ }, { id: 2, name: ‘Doug’ }]

  • options (Hash) (defaults to: {})

    JU’s options e.g.: { filter: false, paginate: false }

Returns:

  • (Boolean)


34
35
36
37
# File 'lib/jsonapi/utils/support/filter/default.rb', line 34

def apply_filter?(records, options = {})
  params[:filter].present? && records.respond_to?(:where) &&
    (options[:filter].nil? || options[:filter])
end

#filter_paramsHash, NilClass

Build a Hash with the default filters.

Returns:

  • (Hash, NilClass)


44
45
46
47
48
49
50
51
52
53
# File 'lib/jsonapi/utils/support/filter/default.rb', line 44

def filter_params
  @_filter_params ||=
    case params[:filter]
    when Hash, ActionController::Parameters
      default_filters.each_with_object({}) do |field, hash|
        unformatted_field = @request.unformat_key(field)
        hash[unformatted_field] = params[:filter][field]
      end
    end
end