Created
April 30, 2013 15:19
-
-
Save tlowrimore/5489414 to your computer and use it in GitHub Desktop.
Sluggo.
This file contains 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
module Sluggo::Controller | |
MATCHER = /(^.+)-(.*$)/ | |
def self.included(base) | |
base.send :include, InstanceMethods | |
end | |
module InstanceMethods | |
private | |
def deslugify | |
params[:id] = $2 if MATCHER =~ params[:id] | |
end | |
end | |
end |
This file contains 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
module Sluggo::Model | |
def self.included(base) | |
base.send :extend, ClassMethods | |
base.send :include, InstanceMethods | |
base.send :before_validation, :slugify | |
end | |
module ClassMethods | |
attr_reader :slug_source_field, :slug_destination_field | |
def sluggo(options={}) | |
@slug_source_field = options[:source] || (raise ArgumentError, "sluggo requires a 'source'.") | |
@slug_destination_field = options[:destination] || :slug | |
end | |
end | |
module InstanceMethods | |
def to_param | |
send self.class.slug_destination_field | |
end | |
private | |
def slugify | |
prefix = send(self.class.slug_source_field).parameterize | |
send "#{self.class.slug_destination_field}=", "#{prefix}-#{id}" | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment