Skip to content

Instantly share code, notes, and snippets.

@firedev
Last active December 13, 2015 16:48
Show Gist options
  • Save firedev/4943289 to your computer and use it in GitHub Desktop.
Save firedev/4943289 to your computer and use it in GitHub Desktop.
Creates :slug from given :title when creating models if no :slug given
# autoslug.rb
#
# Usage:
#
# include Autoslug
# attr_slug :title [, :slug] [, &block]
#
# Creates :slug from given :title when creating models if no :slug given
# Uses parameterize by default or can run :title through a &block:
#
# include Autoslug
# attr_slug(:title) { |s| s.parameterize.tr('-', '') }
#
module Autoslug
def self.included(base)
def base.attr_slug(title_attr, slug_attr = :slug, &block )
def create_slug(title_attr, slug_attr, &block)
self.send("#{slug_attr}=", (
if block_given?
yield(self.send(title_attr))
else
self.send(title_attr).parameterize
end
)
) unless send(slug_attr)
end
self.send :after_initialize do
create_slug(title_attr, slug_attr, &block)
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment