Simple slug functionality for your ActiveRecord objects
Add this line to your application's Gemfile:
gem 'slugworth'and then execute
bundleor
install it yourself with
gem install slugworthGetting started is easy! Just ensure that your model has a database column of type String called slug
To use, just add two declarations to your ActiveRecord class and away you go!
class User < ActiveRecord::Base
include Slugworth
slugged_with :name
endAfter you include the Slugworth module, all you need to do is declare what method will be used to create the slug. The method passed to slugged_with will then be parameterized.
This provides most of the default slug functionality you would need.
- Finders
.find_by_slug&.find_by_slug!are provided. This will, of course, do what you expect and find a single record by the slug attribute provided. #to_paramhas been defined as a parameterized version of the attribute declared toslugged_with.- Validations stating that
slugis present and unique in the database.
By default the slug is unique to the entire table, but you can specify the scope of the uniqueness as the following:
class Product < ActiveRecord::Base
include Slugworth
belongs_to :user
slugged_with :name, scope: :user_id
endSometimes you want to update the slug if the attribute is changed.
class User < ActiveRecord::Base
include Slugworth
slugged_with :name, updatable: true
end
user = User.create(name: 'Jack')
=> User(id: 1, name: 'Jack', slug: 'jack')
user.update_attribute(:name, 'John')
=> User(id: 1, name: 'John', slug: 'john')If another record already exists with the same slug it will generate an uniqueness validation error, but if incremental slugs is enabled, then it will append an incremented number to the slug:
class User < ActiveRecord::Base
include Slugworth
slugged_with :name, incremental: true
end
User.create(name: 'Jack')
=> User(id: 1, name: 'Jack', slug: 'jack')
User.create(name: 'Jack')
=> User(id: 2, name: 'Jack', slug: 'jack-1')To aid in testing your models that implement the Slugworth functionality, I've added a shared example group that can be added to your test suite. Add this to your spec_helper.rb
include 'slugworth_shared_examples'And then in your specs just add:
it_behaves_like :has_slug_functionalityThis will add the same specs to your model that get run on Slugworth itself!
- Fork it
- Create your feature branch (
git checkout -b my-new-feature) - Commit your changes (
git commit -am 'Add some feature') - Push to the branch (
git push origin my-new-feature) - Create new Pull Request
- Rye Mason for the fantastic heading image.
Slugworth is supported by the team at Hashrocket, a multidisciplinary design and development consultancy. If you'd like to work with us or join our team, don't hesitate to get in touch.
