Module: FetcheableOnApi::Filterable::ClassMethods

Defined in:
lib/fetcheable_on_api/filterable.rb

Overview

Class methods made available to controllers when Filterable is included.

Since:

  • 0.1.0

Instance Method Summary collapse

Instance Method Details

#filter_by(*attrs) ⇒ Object

Define one or more filterable attributes for the controller.

This method configures which model attributes can be filtered via query parameters and how those filters should be processed.

Examples:

Basic attribute filtering

filter_by :name, :email, :status
# Allows: filter[name]=john&filter[email][email protected]&filter[status]=active

Custom predicate

filter_by :age, with: :gteq  # Greater than or equal
filter_by :created_at, with: :between, format: :datetime
# Allows: filter[age]=18&filter[created_at]=1609459200,1640995200

Association filtering

filter_by :author, class_name: User, as: 'name'
# Allows: filter[author]=john (filters by users.name)

Custom lambda predicate

filter_by :full_name, with: -> (collection, value) {
  collection.arel_table[:first_name].matches("%#{value}%").or(
    collection.arel_table[:last_name].matches("%#{value}%")
  )
}

Parameters:

  • attrs (Array<Symbol>)

    List of attribute names to make filterable

  • options (Hash)

    Configuration options for the filters

Raises:

See Also:

Since:

  • 0.1.0



139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
# File 'lib/fetcheable_on_api/filterable.rb', line 139

def filter_by(*attrs)
  options = attrs.extract_options!
  options.symbolize_keys!

  # Validate that only supported options are provided
  options.assert_valid_keys(:as, :class_name, :with, :format, :association)

  # Create a new configuration hash to avoid modifying parent class config
  self.filters_configuration = filters_configuration.dup

  attrs.each do |attr|
    # Initialize default configuration for this attribute
    filters_configuration[attr] ||= {
      as: options[:as] || attr
    }

    # Merge in the provided options
    filters_configuration[attr].merge!(options)
  end
end