Created
December 29, 2009 22:44
-
-
Save nz/265675 to your computer and use it in GitHub Desktop.
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
class AddRandomSlugToReports < ActiveRecord::Migration | |
def self.up | |
change_table :reports do |t| | |
t.string :slug | |
t.index :slug | |
end | |
Report.reset_column_information | |
Report.all.each do |report| | |
report.generate_slug! | |
report.save | |
end | |
end | |
def self.down | |
change_table :reports do |t| | |
t.remove :slug | |
t.remove_index :slug | |
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
class Report | |
before_create :generate_slug! | |
# There are a lot of ways to generate slugs. SecureRandom.hex is easy enough. | |
# You need to test for uniqueness -- sometimes I'll use a loop counter as | |
# the param for SecureRandom.hex, so we still get to favor short URLs | |
# without worrying too much about collisions. | |
# The only other change I might make to this would be to generate a | |
# random slug from a different character set. For example, avoiding | |
# phonetically or graphically similar characters. | |
def generate_slug! | |
unless slug.present? | |
slug_size = 2 | |
self.slug = ActiveSupport::SecureRandom.hex(slug_size) | |
while self.count(slug) > 0 | |
count = count + 1 | |
self.slug = ActiveSupport::SecureRandom.hex(slug_size) | |
end | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment