Mongoid LocalizedSlug

WARNING: This is a simplified version of the mongoid-slug gem that supports localized fields. It DOES NOT support nor embedded objects neither slug history. If you need any of those features stick with the original gem.

Mongoid LocalizedSlug generates a URL slug or permalink based on one localized fields in a Mongoid model. It sits idly on top of stringex, supporting non-Latin characters.

Installation

Add to your Gemfile:

gem 'mongoid_localized_slug'

Usage

Set up a slug:

class Book
  include Mongoid::Document
  include Mongoid::LocalizedSlug

  field :title, localize: true
  slug :title, index: true
end

Create a record with multiple translations:

I18n.locale = :en
book = Book.create(:title => "A Thousand Plateaus")
book.to_param    # => "a-thousand-plateaus"
I18n.locale = :es
book.update_attribute :title, 'Mil Mesetas'
book.to_param    #=> "mil-mesetas"

WARNING: DO NOT write directly to the 'slug' attribute because it's now an Array and not a String field. Use always the slugged attribute (Book#title in this case).

Find a record by its slug:

# GET /books/a-thousand-plateaus
book = Book.find_by_slug params[:book_id]
# or just:
book = Book.find params[:book_id]
# GET /books/mil-mesetas
book = Book.find params[:book_id] # matches the same Book object
# Book.find can also find by ID
book = Book.find '5016a912d592cec236000002'

Reserved Slugs

Pass words you do not want to be slugged using the reserve option:

class Friend
  include Mongoid::Document

  field :name
  slug :name, reserve: ['admin', 'root']
end

friend = Friend.create name: 'admin'
Friend.find_by_slug('admin') # => nil
friend.slug # => 'admin-1'