Last active
December 13, 2015 16:48
-
-
Save firedev/4943289 to your computer and use it in GitHub Desktop.
Creates :slug from given :title when creating models 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
# 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