Mongoid Slug generates a URL slug or permalink based on one or more fields in a Mongoid model. It sits idly on top of stringex, supporting non-Latin characters.
CI collects SimpleCov coverage on Ruby 3.4 with Mongoid 9 and MongoDB 8.0 and submits one report to Coveralls using GitHub's workflow token. To generate a local report, run COVERAGE=true MONGOID_VERSION=9 bundle install followed by COVERAGE=true MONGOID_VERSION=9 bundle exec rake spec. Reports are written to coverage/.
Mongoid Slug 7.x requires at least Mongoid 7.0.0 and Ruby 2.7.0. For earlier Mongoid and Ruby version support, please use an earlier version of Mongoid Slug.
Mongoid Slug is compatible with all MongoDB versions which Mongoid supports, however, please see "Slug Max Length" section below for MongoDB 4.0 and earlier.
Add to your Gemfile:
gem 'mongoid-slug'class Book
include Mongoid::Document
include Mongoid::Slug
field :title
slug :title
end# GET /books/a-thousand-plateaus
book = Book.find params[:book_id]Mongoid Slug will attempt to determine whether you want to find using the slugs field or the _id field by inspecting the supplied parameters.
- Mongoid Slug will perform a find based on
slugsonly if all arguments passed tofindare of the typeString. - If your document uses
BSON::ObjectIdidentifiers, and all arguments look like validBSON::ObjectId, then Mongoid Slug will perform a find based on_id. - If your document uses any other type of identifiers, and all arguments passed to
findare of the same type, then Mongoid Slug will perform a find based on_id. - If your document uses
Stringidentifiers and you want to be able find by slugs or ids, to get the correct behavior, you should add aslug_id_strategyoption to your_idfield definition. This option should return something that responds tocall(a callable) and takes one string argument, e.g. a lambda. This callable must return true if the string looks like one of your ids.
Book.fields['_id'].type
# => String
book = Book.find 'a-thousand-plateaus' # Finds by slugs
# => ...
class Post
include Mongoid::Document
include Mongoid::Slug
field :_id, type: String, slug_id_strategy: lambda { |id| id.start_with?('...') }
field :name
slug :name, history: true
end
Post.fields['_id'].type
# => String
post = Post.find 'a-thousand-plateaus' # Finds by slugs
# => ...
post = Post.find '50b1386a0482939864000001' # Finds by bson ids
# => ...Examine slug.rb for all available options.
To set slugs for existing records run following rake task:
rake mongoid_slug:setYou can pass model names as an option for which you want to set slugs:
rake mongoid_slug:set[Model1,Model2]Empty slugs are possible and generate a nil value for the _slugs field. In the Post example above, a blank post name will cause the document record not to contain a _slugs field in the database. The default _slugs index is sparse, allowing that. If you wish to change this behavior add a custom validates_presence_of :_slugs validator to the document or change the database index to sparse: false.
By default Mongoid Slug generates slugs with stringex. If this is not desired you can define your own slug generator.
There are two ways to define slug generator.
Configure a block in config/initializers/mongoid_slug.rb as follows:
Mongoid::Slug.configure do |c|
# create a block that takes the current object as an argument and return the slug
c.slug = proc { |cur_obj|
cur_object.slug_builder.to_url
}
endclass Caption
include Mongoid::Document
include Mongoid::Slug
# create a block that takes the current object as an argument and returns the slug
slug do |cur_object|
cur_object.slug_builder.to_url
end
endThe to_url method comes from stringex.
You can define a slug builder globally and/or override it per model.
By default, Mongoid Slug will automatically generate an index for the slug, which will be created when you run rake db:create_indexes. This index will take into account scoping and other options described below.
To skip this index generation, you may set index: false as follows:
class Employee
include Mongoid::Document
include Mongoid::Slug
field :name
slug :name, index: false
endWith automatic declaration disabled, declare your own Mongoid index with index(...). Changing a declaration does not replace an existing database index: inspect the deployed indexes, check for conflicting data, and explicitly migrate the affected index before recreating it. Do not drop unrelated application indexes.
To scope a slug by a reference association, pass :scope:
class Company
include Mongoid::Document
has_many :employees
end
class Employee
include Mongoid::Document
include Mongoid::Slug
field :name
belongs_to :company, optional: true
slug :name, scope: :company
endIn this example, if you create an employee without associating it with any company, the scope will fall back to the root employees collection.
Currently, if you have an irregular association name, you must specify the :inverse_of option on the other side of the association.
Embedded objects are automatically scoped by their parent.
The index on Employee is derived from the scope and uses { company_id: 1, _slugs: 1 }. Scoped indexes are not declared unique by default. Declare belongs_to :company before slug so the association resolves to company_id rather than company. Use optional: true only when employees without a company are allowed. An alternative is to scope to the field itself as follows:
class Employee
include Mongoid::Document
include Mongoid::Slug
field :name
field :company_id
slug :name, scope: :company_id
endScoped slugs are not globally unique. Routes must carry the scope as well as the slug, for example nested company/employee routes, and controllers must look up the employee through that scope (company.employees.find(params[:id])), not Employee.find(params[:id]). If the route cannot carry the scope, pass the database ID to the route helper instead.
You may scope slugs using multiple fields as per the following example:
class Employee
include Mongoid::Document
include Mongoid::Slug
field :name
field :company_id
field :department_id
# Scope slug uniqueness by a combination of company and department
slug :name, scope: %i[company_id department_id]
endMongoDB featureCompatibilityVersion "4.0" and earlier applies an Index Key Limit which limits the total size of an index entry to around 1KB and will raise error, 17280 - key too large to index when trying to create a record that causes an index key to exceed that limit. By default slugs are of the form text[-number] and the text portion is limited in size to Mongoid::Slug::MONGO_INDEX_KEY_LIMIT_BYTES - 32 bytes. You can change this limit with max_length or set it to nil if you're running MongoDB with failIndexKeyTooLong set to false.
class Company
include Mongoid::Document
include Mongoid::Slug
field :name
slug :name, max_length: 24
endBy default when using STI, the scope will be around the super-class.
class Book
include Mongoid::Document
include Mongoid::Slug
field :title
slug :title, history: true
embeds_many :subjects
has_many :authors
end
class ComicBook < Book
end
book = Book.create(title: 'Anti Oedipus')
comic_book = ComicBook.create(title: 'Anti Oedipus')
comic_book.slugs.should_not eql(book.slugs)If you want the scope to be around the subclass, then set the option by_model_type: true.
class Book
include Mongoid::Document
include Mongoid::Slug
field :title
slug :title, history: true, by_model_type: true
embeds_many :subjects
has_many :authors
end
class ComicBook < Book
end
book = Book.create(title: 'Anti Oedipus')
comic_book = ComicBook.create(title: 'Anti Oedipus')
comic_book.slugs.should eql(book.slugs)Enable slug history tracking by setting history: true.
History retains previous slugs for lookup; it does not generate multiple independent slugs from different source fields. The most recent slug is used for URLs. To switch new URLs back to database IDs while keeping historical lookup, retain Mongoid::Slug, its slug declaration, and the stored history, but override the model's to_param to return id.to_s. Existing slug URLs can still resolve through find; your controller can redirect them to the canonical ID URL. Do not change the slug source to :id, which generates slugs instead of changing URL selection.
class Page
include Mongoid::Document
include Mongoid::Slug
field :title
slug :title, history: true
endThe document will then be returned for any of the saved slugs:
page = Page.new title: "Home"
page.save
page.update_attributes title: "Welcome"
Page.find("welcome") == Page.find("home") # => truePass 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('admin') # => nil
friend.slug # => 'admin-1'When reserved words are not specified, the words 'new' and 'edit' are considered reserved by default. Specifying an array of custom reserved words will overwrite these defaults.
The slugs can be localized. This feature is built upon Mongoid localized fields, so fallbacks and localization works as documented in the Mongoid manual.
class PageSlugLocalize
include Mongoid::Document
include Mongoid::Slug
field :title, localize: true
slug :title, localize: true
endBy specifying localize: true, the slug index will be created on the I18n.default_locale field only. For example, if I18n.default_locale is :en, the index will be generated as follows:
slug :title, localize: true
# The following index is auto-generated:
index({ '_slugs.en' => 1 }, { unique: true, sparse: true })If you are supporting multiple locales, you may specify the list of locales on which to create indexes as an Array.
slug :title, localize: [:fr, :es, :de]
# The following indexes are auto-generated:
index({ '_slugs.fr' => 1 }, { unique: true, sparse: true })
index({ '_slugs.es' => 1 }, { unique: true, sparse: true })
index({ '_slugs.de' => 1 }, { unique: true, sparse: true })By default find will search for the document by the id field if the provided id looks like a BSON::ObjectId, and it will otherwise find by the _slugs field. However, custom strategies can override the default behavior, like e.g:
module Mongoid::Slug::UuidIdStrategy
def self.call id
id =~ /\A([0-9a-fA-F]){8}-(([0-9a-fA-F]){4}-){3}([0-9a-fA-F]){12}\z/
end
endUse a custom strategy by adding the slug_id_strategy annotation to the _id field:
class Entity
include Mongoid::Document
include Mongoid::Slug
field :_id, type: String, slug_id_strategy: UuidIdStrategy
field :user_edited_variation
slug :user_edited_variation, history: true
endLets say you want to have a auto-suggest function on your GUI that could provide a preview of what the url or slug could be before the form to create the record was submitted.
You can use the UniqueSlug class in your server side code to do this, e.g.
title = params[:title]
unique = Mongoid::Slug::UniqueSlug.new(Book.new).find_unique(title)
# ...
# return some representation of uniqueSee CONTRIBUTING.md, CHANGELOG.md, UPGRADING.md, and RELEASING.md.
Copyright (c) 2010-2017 Hakan Ensari & Contributors, see LICENSE for details.