Last active
April 11, 2018 07:19
-
-
Save rodloboz/e7d4ddf93dd147a47f4ce9a18fb5137b to your computer and use it in GitHub Desktop.
Rails Slug Filtering
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # Set up a /slug/ route to your #index in routes.rb | |
| # get '/search/:slug', to: 'restaurants#index' | |
| class RestaurantsController < ApplicationController | |
| def index | |
| if params[:slug] | |
| lookup = SlugLookupService.new(params[:slug]) | |
| lookup.perform | |
| category = lookup.category | |
| redirect_to restaurants_path unless category | |
| end | |
| query = params[:q].presence || "*" # elastic search needs a default 'get all' query | |
| @restaurants = RestaurantSearchService.new(category || nil, query, params).perform | |
| end | |
| end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # Dictionary is a PORO (plain ruby class) | |
| # that contains an hash like structure: | |
| # { "slug-name" => { id: 1, text: "category_name"} } | |
| # and some util method to order terms and do internal searches | |
| # which will allow to have more complex slugging rules | |
| class SlugLookupService | |
| attr_reader :category | |
| def initialize(slug) | |
| @slug = slug | |
| @dictionary = Dictionary.new | |
| @category = nil | |
| end | |
| def perform | |
| lookup_slug | |
| end | |
| private | |
| def lookup_slug | |
| @dictionary.ordered_terms.each_with_index do |term, index| | |
| if @slug == term | |
| @category = @dictionary.text(term) | |
| end | |
| end | |
| end | |
| end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment