{"id":13846968,"url":"https://github.com/mongoid/mongoid-slug","last_synced_at":"2025-04-09T11:05:07.872Z","repository":{"id":47827442,"uuid":"733570","full_name":"mongoid/mongoid-slug","owner":"mongoid","description":"Generates a URL slug/permalink based on fields in a Mongoid-based model.","archived":false,"fork":false,"pushed_at":"2023-10-23T17:40:41.000Z","size":624,"stargazers_count":494,"open_issues_count":13,"forks_count":165,"subscribers_count":20,"default_branch":"master","last_synced_at":"2024-04-13T22:59:42.439Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":"https://github.com/mongoid/mongoid-slug","language":"Ruby","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/mongoid.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":"CONTRIBUTING.md","funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null}},"created_at":"2010-06-22T09:39:11.000Z","updated_at":"2024-04-12T14:20:41.000Z","dependencies_parsed_at":"2024-01-18T09:04:40.156Z","dependency_job_id":"56cdd103-7f56-4363-ae7d-b41612bd3528","html_url":"https://github.com/mongoid/mongoid-slug","commit_stats":{"total_commits":516,"total_committers":55,"mean_commits":9.381818181818181,"dds":0.562015503875969,"last_synced_commit":"58917341eec480be55015ed5651cd6987e509c25"},"previous_names":["digitalplaywright/mongoid-slug"],"tags_count":36,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/mongoid%2Fmongoid-slug","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/mongoid%2Fmongoid-slug/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/mongoid%2Fmongoid-slug/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/mongoid%2Fmongoid-slug/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/mongoid","download_url":"https://codeload.github.com/mongoid/mongoid-slug/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":248027406,"owners_count":21035594,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2024-08-04T18:00:51.404Z","updated_at":"2025-04-09T11:05:07.842Z","avatar_url":"https://github.com/mongoid.png","language":"Ruby","funding_links":[],"categories":["Ruby"],"sub_categories":[],"readme":"Mongoid Slug\n============\n\nMongoid Slug generates a URL slug or permalink based on one or more fields in a Mongoid model.\nIt sits idly on top of [stringex](https://github.com/rsl/stringex), supporting non-Latin characters.\n\n[![Build Status](https://github.com/mongoid/mongoid-slug/actions/workflows/test.yml/badge.svg?query=branch%3Amaster)](https://github.com/mongoid/mongoid-slug/actions/workflows/test.ym?query=branch%3Amaster)\n[![Gem Version](https://badge.fury.io/rb/mongoid-slug.svg)](http://badge.fury.io/rb/mongoid-slug)\n[![Code Climate](https://codeclimate.com/github/mongoid/mongoid-slug.svg)](https://codeclimate.com/github/mongoid/mongoid-slug)\n\n### Version Support\n\nMongoid 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.\n\nMongoid Slug is compatible with all MongoDB versions which Mongoid supports, however, please see \"Slug Max Length\" section below for MongoDB 4.0 and earlier.\n\n### Installation\n\nAdd to your Gemfile:\n\n```ruby\ngem 'mongoid-slug'\n```\n\n### Usage\n\n### Set Up a Slug\n\n```ruby\nclass Book\n  include Mongoid::Document\n  include Mongoid::Slug\n\n  field :title\n  slug :title\nend\n```\n\n### Find a Document by its Slug\n\n```ruby\n# GET /books/a-thousand-plateaus\nbook = Book.find params[:book_id]\n```\n\nMongoid Slug will attempt to determine whether you want to find using the `slugs` field or the `_id` field by inspecting the supplied parameters.\n\n* Mongoid Slug will perform a find based on `slugs` only if all arguments passed to `find` are of the type `String`.\n* 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`.\n* 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`.\n* 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.\n\n```ruby\nBook.fields['_id'].type\n=\u003e String\n\nbook = Book.find 'a-thousand-plateaus' # Finds by slugs\n=\u003e ...\n\nclass Post\n  include Mongoid::Document\n  include Mongoid::Slug\n\n  field :_id, type: String, slug_id_strategy: lambda { |id| id.start_with?('...') }\n\n  field :name\n  slug  :name, history: true\nend\n\nPost.fields['_id'].type\n=\u003e String\n\npost = Post.find 'a-thousand-plateaus' # Finds by slugs\n=\u003e ...\n\npost = Post.find '50b1386a0482939864000001' # Finds by bson ids\n=\u003e ...\n```\n\n[Examine slug.rb](lib/mongoid/slug.rb) for all available options.\n\n### Updating Existing Records\n\nTo set slugs for existing records run following rake task:\n\n```ruby\nrake mongoid_slug:set\n```\n\nYou can pass model names as an option for which you want to set slugs:\n\n```ruby\nrake mongoid_slug:set[Model1,Model2]\n```\n\n### Nil Slugs\n\nEmpty 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`.\n\n### Custom Slug Generation\n\nBy default Mongoid Slug generates slugs with stringex. If this is not desired you can define your own slug generator.\n\nThere are two ways to define slug generator.\n\n#### Globally\n\nConfigure a block in `config/initializers/mongoid_slug.rb` as follows:\n\n```ruby\nMongoid::Slug.configure do |c|\n  # create a block that takes the current object as an argument and return the slug\n  c.slug = proc { |cur_obj|\n    cur_object.slug_builder.to_url\n  }\nend\n```\n\n#### On Model\n\n```ruby\nclass Caption\n  include Mongoid::Document\n  include Mongoid::Slug\n\n  # create a block that takes the current object as an argument and returns the slug\n  slug do |cur_object|\n    cur_object.slug_builder.to_url\n  end\nend\n```\n\nThe `to_url` method comes from [stringex](https://github.com/rsl/stringex).\n\nYou can define a slug builder globally and/or override it per model.\n\n### Indexing\n\nBy 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.\n\nTo skip this index generation, you may set `index: false` as follows:\n\n```ruby\nclass Employee\n  include Mongoid::Document\n  include Mongoid::Slug\n\n  field :name\n\n  slug :name, index: :false\nend\n```\n\n### Scoping\n\nTo scope a slug by a reference association, pass `:scope`:\n\n```ruby\nclass Company\n  include Mongoid::Document\n\n  references_many :employees\nend\n\nclass Employee\n  include Mongoid::Document\n  include Mongoid::Slug\n\n  field :name\n  referenced_in :company\n\n  slug :name, scope: :company\nend\n```\n\nIn this example, if you create an employee without associating it with any company, the scope will fall back to the root employees collection.\n\nCurrently, if you have an irregular association name, you **must** specify the `:inverse_of` option on the other side of the assocation.\n\nEmbedded objects are automatically scoped by their parent.\n\nNote that the unique index on the `Employee` collection in this example is derived from the `scope` value and is `{ _slugs: 1, company_id: 1}`. Therefore `:company` must be `referenced_in` above the definition of `slug` or it will not be able to resolve the association and mistakenly create a `{ _slugs: 1, company: 1}` index. An alternative is to scope to the field itself as follows:\n\n```ruby\nclass Employee\n  include Mongoid::Document\n  include Mongoid::Slug\n\n  field :name\n  field :company_id\n\n  slug :name, scope: :company_id\nend\n```\n\nYou may scope slugs using multiple fields as per the following example:\n\n```ruby\nclass Employee\n  include Mongoid::Document\n  include Mongoid::Slug\n\n  field :name\n  field :company_id\n  field :department_id\n\n  # Scope slug uniqueness by a combination of company and department\n  slug :name, scope: %i[company_id department_id]\nend\n```\n\n### Slug Max Length\n\nMongoDB [featureCompatibilityVersion](https://docs.mongodb.com/manual/reference/command/setFeatureCompatibilityVersion/#std-label-view-fcv)\n\"4.0\" and earlier applies an [Index Key Limit](https://docs.mongodb.com/manual/reference/limits/#mongodb-limit-Index-Key-Limit)\nwhich limits the total size of an index entry to around 1KB and will raise error,\n`17280 - key too large to index` when trying to create a record that causes an index key to exceed that limit.\nBy default slugs are of the form `text[-number]` and the text portion is limited in size\nto `Mongoid::Slug::MONGO_INDEX_KEY_LIMIT_BYTES - 32` bytes.\nYou can change this limit with `max_length` or set it to `nil` if you're running MongoDB\nwith [failIndexKeyTooLong](https://docs.mongodb.org/manual/reference/parameters/#param.failIndexKeyTooLong) set to `false`.\n\n```ruby\nclass Company\n  include Mongoid::Document\n  include Mongoid::Slug\n\n  field :name\n\n  slug  :name, max_length: 24\nend\n```\n\n### Optionally Find and Create Slugs per Model Type\n\nBy default when using STI, the scope will be around the super-class.\n\n```ruby\nclass Book\n  include Mongoid::Document\n  include Mongoid::Slug\n  field :title\n\n  slug  :title, history: true\n  embeds_many :subjects\n  has_many :authors\nend\n\nclass ComicBook \u003c Book\nend\n\nbook = Book.create(title: 'Anti Oedipus')\ncomic_book = ComicBook.create(title: 'Anti Oedipus')\ncomic_book.slugs.should_not eql(book.slugs)\n```\n\nIf you want the scope to be around the subclass, then set the option `by_model_type: true`.\n\n```ruby\nclass Book\n  include Mongoid::Document\n  include Mongoid::Slug\n  field :title\n\n  slug  :title, history: true, by_model_type: true\n  embeds_many :subjects\n  has_many :authors\nend\n\nclass ComicBook \u003c Book\nend\n\nbook = Book.create(title: 'Anti Oedipus')\ncomic_book = ComicBook.create(title: 'Anti Oedipus')\ncomic_book.slugs.should eql(book.slugs)\n```\n\n### History\n\nEnable slug history tracking by setting `history: true`.\n\n```ruby\nclass Page\n  include Mongoid::Document\n  include Mongoid::Slug\n\n  field :title\n\n  slug :title, history: true\nend\n```\n\nThe document will then be returned for any of the saved slugs:\n\n```ruby\npage = Page.new title: \"Home\"\npage.save\npage.update_attributes title: \"Welcome\"\n\nPage.find(\"welcome\") == Page.find(\"home\") # =\u003e true\n```\n\n### Reserved Slugs\n\nPass words you do not want to be slugged using the `reserve` option:\n\n```ruby\nclass Friend\n  include Mongoid::Document\n\n  field :name\n  slug :name, reserve: ['admin', 'root']\nend\n\nfriend = Friend.create name: 'admin'\nFriend.find('admin') # =\u003e nil\nfriend.slug # =\u003e 'admin-1'\n```\n\nWhen reserved words are not specified, the words 'new' and 'edit' are considered reserved by default.\nSpecifying an array of custom reserved words will overwrite these defaults.\n\n### Localize Slugs\n\nThe slugs can be localized. This feature is built upon Mongoid localized fields,\nso fallbacks and localization works as documented in the Mongoid manual.\n\n```ruby\nclass PageSlugLocalize\n  include Mongoid::Document\n  include Mongoid::Slug\n\n  field :title, localize: true\n  slug  :title, localize: true\nend\n```\n\nBy specifying `localize: true`, the slug index will be created on the\n[I18n.default_locale](http://guides.rubyonrails.org/i18n.html#the-public-i18n-api) field only.\nFor example, if `I18n.default_locale` is `:en`, the index will be generated as follows:\n\n```ruby\nslug :title, localize: true\n\n# The following index is auto-generated:\nindex({ '_slugs.en' =\u003e 1 }, { unique: true, sparse: true })\n```\n\nIf you are supporting multiple locales, you may specify the list of locales on which\nto create indexes as an `Array`.\n\n```ruby\nslug :title, localize: [:fr, :es, :de]\n\n# The following indexes are auto-generated:\nindex({ '_slugs.fr' =\u003e 1 }, { unique: true, sparse: true })\nindex({ '_slugs.es' =\u003e 1 }, { unique: true, sparse: true })\nindex({ '_slugs.de' =\u003e 1 }, { unique: true, sparse: true })\n```\n\n### Custom Find Strategies\n\nBy 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:\n\n```ruby\nmodule Mongoid::Slug::UuidIdStrategy\n  def self.call id\n    id =~ /\\A([0-9a-fA-F]){8}-(([0-9a-fA-F]){4}-){3}([0-9a-fA-F]){12}\\z/\n  end\nend\n```\n\nUse a custom strategy by adding the `slug_id_strategy` annotation to the `_id` field:\n\n```ruby\nclass Entity\n  include Mongoid::Document\n  include Mongoid::Slug\n\n  field :_id, type: String, slug_id_strategy: UuidIdStrategy\n\n  field :user_edited_variation\n  slug  :user_edited_variation, history: true\nend\n```\n\n### Adhoc Checking Whether a Slug is Unique\n\nLets 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.\n\nYou can use the UniqueSlug class in your server side code to do this, e.g.\n\n```ruby\ntitle = params[:title]\nunique = Mongoid::Slug::UniqueSlug.new(Book.new).find_unique(title)\n...\n# return some representation of unique\n```\n\nContributing\n------------\n\nMongoid-slug is work of [many of contributors](https://github.com/mongoid/mongoid-slug/graphs/contributors). You're encouraged to submit [pull requests](https://github.com/mongoid/mongoid-slug/pulls), [propose features, ask questions and discuss issues](https://github.com/mongoid/mongoid-slug/issues). See [CONTRIBUTING](CONTRIBUTING.md) for details.\n\nCopyright \u0026 License\n-------------------\n\nCopyright (c) 2010-2017 Hakan Ensari \u0026 Contributors, see [LICENSE](LICENSE) for details.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmongoid%2Fmongoid-slug","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fmongoid%2Fmongoid-slug","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmongoid%2Fmongoid-slug/lists"}