Skip to content

Instantly share code, notes, and snippets.

@firedev
Last active August 29, 2015 13:57
Show Gist options
  • Save firedev/9701874 to your computer and use it in GitHub Desktop.
Save firedev/9701874 to your computer and use it in GitHub Desktop.
Creates :slug from given :title if no :slug given
# 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