Search Filters and Object Oriented Design
Search filters are a very common feature in any application.
I’ve used two gems for several projects I worked on: has_scope and searchlight.
Both gems work out of the box, but they are not as flexible as I would like them to be, and that’s why I decided to create my gem, Lupa.
I decided to write an overview about these 3 gems:
HasScope
has_scope will map your controller filters to your model scopes.
app/controllers/products_controller.rb
class ProductsController < ApplicationController
has_scope :featured, type: :boolean
has_scope :by_price
has_scope :by_period, using: [:started_at, :ended_at], type: :hash
def index
@products = apply_scopes(Product).all
end
end
app/models/product.rb
class Product < ActiveRecord::Base
scope :featured, -> { where(featured: true) }
scope :by_price, -> price { where(price: price) }
scope :by_period, -> started_at, ended_at
...