Skip to Content
Course content

209: Building a Faceted Search Feature

Click on the "Edit" button in the top corner of the screen to edit your slide content.

Faceted search sounds like a high-end enterprise feature, but at its core, it's just a way to let users narrow down a large dataset by applying multiple, optional filters. Think of any e-commerce site where you check "Blue," "Size Large," and "Under $50" simultaneously. In Ruby, the trick is to build a flexible system that doesn't break when a user leaves some filters blank.

To keep this concrete, let's build a search feature for a board game collection. We'll want to filter by genre, player count, and complexity.

Setting up our board game data

Before we get to the logic, we need something to search. I'll use a simple array of hashes here. In a real app, this would be an ActiveRecord query, but the logic for handling the facets remains the same.

GAMES = [
  { title: "Terraforming Mars", genre: "Sci-Fi", players: 5, complexity: "High" },
  { title: "Catan", genre: "Strategy", players: 4, complexity: "Medium" },
  { title: "Ticket to Ride", genre: "Strategy", players: 5, complexity: "Low" },
  { title: "Pandemic", genre: "Co-op", players: 4, complexity: "Medium" },
  { title: "Azul", genre: "Abstract", players: 4, complexity: "Low" },
  { title: "Spirit Island", genre: "Co-op", players: 4, complexity: "High" }
]

The first (flawed) attempt at filtering

My first instinct is usually to write a method that takes each facet as an argument and chains a bunch of select calls. Let's see how that looks.

class GameSearch
  def self.search(genre: nil, complexity: nil)
    results = GAMES.select { |g| g[:genre] == genre }
    results = results.select { |g| g[:complexity] == complexity }
    results
  end
end

I'll be honest: I've written this exact pattern a dozen times and then immediately regretted it. Here is the problem: if the user doesn't select a genre (meaning genre is nil), the first select will look for games where the genre is explicitly nil. Since all our games have genres, it returns an empty array immediately. The search "breaks" unless the user fills out every single filter.

Making the filters optional

To fix this, we need to tell Ruby: "Only apply this filter if the user actually provided a value." I prefer using the all? method on the criteria themselves. It's much cleaner than writing a dozen if statements.

I'm going to move the filters into a hash. This makes the code more scalable; if we add a "Year" or "Designer" facet later, we don't have to keep adding arguments to our method.

class GameSearch
  def self.search(filters = {})
    GAMES.select do |game|
      # We check every filter provided by the user
      filters.all? do |key, value|
        # If the user didn't provide a value for this facet, ignore it (return true)
        # Otherwise, check if the game's attribute matches the value
        value.nil? || value.empty? || game[key.to_sym] == value
      end
    end
  end
end

Now, if I call GameSearch.search(complexity: "High"), the genre filter isn't in the hash, so all? only evaluates the complexity. We get "Terraforming Mars" and "Spirit Island" without the search crashing or returning nothing.

Handling multi-select facets

In the real world, users rarely want just one genre. They want "Sci-Fi OR Strategy." To handle this, we should allow the filter values to be arrays. I'll tweak the comparison logic to use include?.

class GameSearch
  def self.search(filters = {})
    GAMES.select do |game|
      filters.all? do |key, value|
        next true if value.nil? || (value.respond_to?(:empty?) && value.empty?)
        
        # Cast the game value to an array so we can use .include? 
        # regardless of whether the filter is a single string or a list
        game_value = game[key.to_sym]
        Array(value).include?(game_value)
      end
    end
  end
end

# Now we can do this:
# GameSearch.search(genre: ["Sci-Fi", "Strategy"])

By wrapping value in Array(), I'm normalizing the input. If the user passes a single string "Sci-Fi", it becomes ["Sci-Fi"]. If they pass an array, it stays an array. This is a handy Ruby trick that saves me from writing a lot of type-checking boilerplate.




📋 Practical Task

Build a Multi-Facet Book Catalog Filter

You are building a search feature for a digital bookstore. Create a BookSearch class and a BOOKS constant containing at least 5 books. Each book should have a title, genre (e.g., "Fantasy", "Mystery"), and format (e.g., "Hardcover", "E-book").

Implement a .search(filters = {}) method that allows users to filter by one or both of these facets. Your implementation must satisfy these three requirements:

  • If the filters hash is empty, it should return all books.
  • If a filter is provided as an array (e.g., genre: ["Fantasy", "Mystery"]), it should return books matching any of those genres.
  • The search should not fail or return an empty list if only one of the facets is provided.

Test your code by searching for all "E-books" regardless of genre, and then searching for books that are either "Fantasy" or "Mystery" and are "Hardcover".

Rating
0 0

There are no comments for now.

to be the first to leave a comment.