Skip to content

Commit

Permalink
fixed a bug that caused renamed columns not to work correctly
Browse files Browse the repository at this point in the history
  • Loading branch information
brendan6 committed Oct 12, 2011
1 parent e2c476e commit 22fbfe9
Showing 1 changed file with 20 additions and 16 deletions.
36 changes: 20 additions & 16 deletions lib/has_unique_slug.rb
Expand Up @@ -7,27 +7,20 @@ def self.included(base)

module ClassMethods

def has_unique_slug(*args)

# Setup options Hash
options = {:generates_with => :title, :slug_column => :slug}
options.merge! args.pop if args.last.kind_of? Hash

# Standaridize implementation
title, slug = options[:generates_with], options[:slug_column]
def has_unique_slug(title_col = "title", slug_col = "slug")

# Add ActiveRecord Callback
before_create do |record|

# Add a slug if slug doesn't exist
if record[slug].blank?
record[slug] = record[title].parameterize
if record[slug_col].blank?
record[slug_col] = record[title_col].parameterize
end

# Ensure the current slug is unique in the database, if not, make it unqiue
i = 2
while not record.class.where(slug => record[slug]).count.zero?
record[slug] = "#{record[slug]}-#{i}"
while not record.class.where("#{slug_col} = ?", record[slug_col]).count.zero?
record[slug_col] = "#{record[slug_col]}-#{i}"
i += 1
end
end
Expand All @@ -37,13 +30,24 @@ def has_unique_slug(*args)
include HasUniqueSlug::InstanceMethods
end

# Add class methods to objects using has_unique_slug
# Add configuration mechanism
instance_eval <<-EOV
def slug_column
'#{slug_col}'
end
def title_column
'#{title_col}'
end
EOV

# Add find method to override ActiveRecord::Base.find
instance_eval do
def find(*args)
if args.length == 1
where(slug => args.first).first
where("#{slug_column} = ?", args.first).first
else
where(slug => args)
where("#{slug_column} IN (?)", args)
end
end
end
Expand All @@ -54,7 +58,7 @@ def find(*args)
module InstanceMethods

def to_param
slug
self.send(self.class.slug_column)
end

end
Expand Down

0 comments on commit 22fbfe9

Please sign in to comment.