Last active
August 29, 2015 13:57
-
-
Save firedev/9701874 to your computer and use it in GitHub Desktop.
Creates :slug from given :title if no :slug given
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# app/models/concerns/sluggable_model.rb | |
# | |
# https://gist.github.com/firedev/9701874 | |
# | |
# Usage: | |
# | |
# rails g migration addSlugToModel slug:string:uniq | |
# | |
# include SluggableModel | |
# attr_slug :title [, :slug] [, &block] | |
# | |
# Creates :slug from given :title when saving models if no :slug given | |
# Uses parameterize by default or can run :title through a &block: | |
# | |
# include SluggableModel | |
# attr_slug :title # default handler is .parameterize | |
# | |
# or you can pass a block with your own handler: | |
# attr_slug(:title [, :slug]) { |title| title.transliterate.parameterize } | |
# | |
module SluggableModel | |
extend ActiveSupport::Concern | |
module ClassMethods | |
def attr_slug(title_attr, slug_attr = :slug, &block) | |
before_validation { create_slug(title_attr, slug_attr, &block) } | |
validates slug_attr, presence: true, uniqueness: true if respond_to? slug_attr | |
end | |
end | |
def to_param | |
"#{id}-#{slug}" | |
end | |
def create_slug(title_attr, slug_attr, &block) | |
return if send(title_attr).blank? | |
send "#{slug_attr}=", create_slug_string(title_attr, &block) | |
end | |
def create_slug_string(title_attr, &_block) | |
if block_given? | |
yield send(title_attr).to_s | |
else | |
send(title_attr).to_s.parameterize | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment