Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Generates a URL slug/permalink based on fields in a Mongoid-based model
Ruby

This branch is 13 commits ahead, 210 commits behind digitalplaywright:master

Fetching latest commit…

Cannot retrieve the latest commit at this time

Failed to load latest commit information.
lib
spec
.gitignore
.travis.yml
CHANGELOG.md
Gemfile
LICENSE
README.md
Rakefile
mongoid_slug.gemspec

README.md

Mongoid Slug

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.

travis

Installation

Add to your Gemfile:

gem 'mongoid_slug'

Usage

Set up a slug:

class Book
  include Mongoid::Document
  include Mongoid::Slug

  field :title
  slug :title
end

Find a record by its slug:

# GET /books/a-thousand-plateaus
book = Book.find_by_slug params[:book_id]

Read here for all available options.

Scoping

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

  slug  :name, :scope => :company
end

In 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 assocation.

Embedded objects are automatically scoped by their parent.

The value of :scope can alternatively be a field within the model itself:

class Employee
  include Mongoid::Document
  include Mongoid::Slug

  field :name
  field :company_id

  slug  :name, :scope => :company_id
end

History

To specify that the history of a document should be kept track of, pass :history with a value of true.

class Page
  include Mongoid::Document
  include Mongoid::Slug

  field :title

  slug :title, history: true
end

The 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_by_slug("welcome") == Page.find_by_slug("home") #=> true

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'
Something went wrong with that request. Please try again.