Skip to content

Instantly share code, notes, and snippets.

@tlowrimore
Created April 30, 2013 15:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tlowrimore/5489414 to your computer and use it in GitHub Desktop.
Save tlowrimore/5489414 to your computer and use it in GitHub Desktop.
Sluggo.
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
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