Code Monkey home page Code Monkey logo

mongoid-slug's Introduction

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.

Build Status Gem Version Dependency Status Code Climate

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 document by its slug:

# 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 slugs only if all arguments passed to find are of the type String
  • If your document uses BSON::ObjectId identifiers, and all arguments look like valid BSON::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 find are of the same type, then Mongoid Slug will perform a find based on _id.
  • If your document uses String identifiers and you want to be able find by slugs or ids, to get the correct behaviour, you should add a slug_id_strategy option to your _id field definition. This option should return something that responds to call (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:set

You can pass model names as an option for which you want to set slugs:

rake mongoid_slug:set[Model1,Model2]

Custom Slug Generation

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

  1. Global definition:

    Configure a block in config/initializers/mongoid_slug.rb as follows:

    Mongoid::Slug.config do |c|
      #create a block that takes the current object as an argument
      #and returns the slug.
      c.slug = proc{|cur_obj|
        cur_object.slug_builder.to_url
      }
    end
  1. Define it on model level:

    class 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
    end

You can call stringex to_url method.

The block defined in the model is given preference over the block defined globally.

Scoping

To scope a slug by a reference association, pass :scope:

class Company
  include Mongoid::Document

  references_many :employees
end

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

  field :name
  referenced_in :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

Limit Slug Length

MongoDB has a default limit around 1KB to the size of the index keys 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
end

Optionally Find and Create Slugs per Model Type

By 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)

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("welcome") == Page.find("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('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.

Localize Slug

The slug can be localized:

class PageSlugLocalize
  include Mongoid::Document
  include Mongoid::Slug

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

This feature is built upon Mongoid localized fields, so fallbacks and localization works as documented in the Mongoid manual.

PS! A migration is needed to use Mongoid localized fields for documents that was created when this feature was off. Anything else will cause errors.

Custom Find Strategies

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 ovveride 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
end

Use 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
end

Adhoc checking whether a string is unique on a per Model basis

Lets 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 unique

Mongoid::Paranoia Support

The Mongoid::Paranoia gem adds "soft-destroy" functionality to Mongoid documents. Mongoid::Slug contains special handling for Mongoid::Paranoia:

  • When destroying a paranoid document, the slug will be unset from the database.
  • When restoring a paranoid document, the slug will be rebuilt. Note that the new slug may not match the old one.
  • When resaving a destroyed paranoid document, the slug will remain unset in the database.
  • For indexing purposes, sparse unique indexes are used. The sparse condition will ignore any destroyed paranoid documents, since their slug is not set in database.
class Entity
  include Mongoid::Document
  include Mongoid::Slug
  include Mongoid::Paranoia
end

The following variants of Mongoid Paranoia are officially supported:

Contributing

Mongoid-slug is work of many of contributors. You're encouraged to submit pull requests, propose features, ask questions and discuss issues. See CONTRIBUTING for details.

Copyright & License

Copyright (c) 2010-2016 Hakan Ensari & Contributors, see LICENSE for details.

mongoid-slug's People

Contributors

hakanensari avatar digitalplaywright avatar dblock avatar astjohn avatar guyboertje avatar douwem avatar empact avatar tiendung avatar johnnyshields avatar lucasrenan avatar ches avatar ajsharp avatar loopj avatar zefer avatar etehtsea avatar xslim avatar siong1987 avatar simi avatar bdmac avatar da-z avatar al avatar zeke avatar klacointe avatar dmathieu avatar trevor avatar sagmor avatar sporkd avatar pdf avatar fxposter avatar iamnader avatar

Watchers

Jiren Patel avatar Sethupathi Asokan avatar kiran  avatar Shailesh avatar sivagollapalli avatar Pratik Shah avatar Anuja Ware avatar Swapnil Chincholkar avatar  avatar James Cloos avatar Rishi avatar atul avatar Anil Kumar Maurya avatar Pramod Shinde avatar Shekhar Sahu avatar Deepak Singh avatar Sachin Shintre avatar Aditya Shedge avatar Anuja Joshi avatar Yogesh Khater avatar Shweta Kale avatar Anurag Pratap avatar Lakshmi Sharma avatar Paritosh Botre avatar Neelam Sharma avatar MohitPawar avatar Amol Udage avatar Ashvini Vibhute avatar Sakshi Parakh avatar Anuj Verma avatar  avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.