Module: FetcheableOnApi::Filterable

Defined in:
lib/fetcheable_on_api/filterable.rb

Overview

Filterable implements support for JSONAPI-compliant filtering via ‘filter` query parameters.

This module enables controllers to process filter parameters in the format: ‘filter=value` or `filter=value1,value2` for multiple values

It supports:

  • 30+ Arel predicates (eq, ilike, between, in, gt, lt, matches, etc.)

  • Association filtering with custom class names

  • Custom lambda predicates for complex filtering logic

  • Multiple filter values with OR logic

  • Date/time filtering with custom formats

Examples:

Basic filtering setup

class UsersController < ApplicationController
  filter_by :name, :email, :status

  def index
    users = apply_fetcheable(User.all)
    render json: users
  end
end

# GET /users?filter[name]=john&filter[status]=active

Association filtering

class PostsController < ApplicationController
  filter_by :title
  filter_by :author, class_name: User, as: 'name'

  def index
    posts = apply_fetcheable(Post.joins(:author))
    render json: posts
  end
end

# GET /posts?filter[author]=john&filter[title]=rails

Custom predicates

class ProductsController < ApplicationController
  filter_by :price, with: :gteq  # Greater than or equal
  filter_by :created_at, with: :between, format: :datetime

  def index
    products = apply_fetcheable(Product.all)
    render json: products
  end
end

# GET /products?filter[price]=100&filter[created_at]=1609459200,1640995200

See Also:

Since:

  • 0.1.0

Defined Under Namespace

Modules: ClassMethods

Constant Summary collapse

PREDICATES_WITH_ARRAY =

Arel predicates that expect array values instead of single values. These predicates work with multiple values and are handled differently during parameter validation and processing.

Arel predicates that expect array values instead of single values.

Examples:

Usage with array predicates

filter_by :tags, with: :in_all
# Expects: filter[tags][]= or filter[tags]=value1,value2

Since:

  • 0.1.0

%i[
  does_not_match_all
  does_not_match_any
  eq_all
  eq_any
  gt_all
  gt_any
  gteq_all
  gteq_any
  in_all
  in_any
  lt_all
  lt_any
  lteq_all
  lteq_any
  matches_all
  matches_any
  not_eq_all
  not_eq_any
  not_in_all
  not_in_any
].freeze

Class Method Summary collapse

Class Method Details

.included(base) ⇒ Object

Hook called when Filterable is included in a class. Sets up the class to support filter configuration and provides the filter_by class method.

Parameters:

  • base (Class)

    The class including this module

Since:

  • 0.1.0



93
94
95
96
97
98
99
100
# File 'lib/fetcheable_on_api/filterable.rb', line 93

def self.included(base)
  base.class_eval do
    extend ClassMethods
    # Store filter configurations per class to avoid conflicts between controllers
    class_attribute :filters_configuration, instance_writer: false
    self.filters_configuration = {}
  end
end