0

I am trying to create a unique numeric permalink in rails. My problem is that I need to make sure it is unique, has between 5 and 7 numbers and is randomly generated (so not simply counting up). I did look at FriendlyID but I am not sure if this can deliver what I need - the url for my permalink should eventually look like this:

www.kreelu.com/4325677

Is there a build in feature or a gem that can provide this?

Thanks!

Paritosh Piplewar
  • 7,982
  • 5
  • 26
  • 41
Thomas Kuhlmann
  • 325
  • 5
  • 13
  • http://stackoverflow.com/questions/1117584/guids-in-ruby – Scott Hunter Apr 04 '14 at 11:02
  • Do you require any security on this? 5 digits is not really enough to be secure if you have even a moderate number (e.g. 10) of valid numbers. Could you clarify the purpose? – Neil Slater Apr 04 '14 at 11:02
  • 1
    I think you can use has_permalink gem. i am not sure your purpose solved but it is helpfull to you. See the url http://haspermalink.org/ – Abid Hussain Apr 04 '14 at 11:05
  • You save the permalinks right? Just use ruby's rand() method with a range excluding the existig permalinks from range – SG 86 Apr 04 '14 at 11:09
  • http://stackoverflow.com/questions/119107/how-do-i-generate-a-list-of-n-unique-random-numbers-in-ruby – SG 86 Apr 04 '14 at 11:14
  • @neilSlater It doesn't need to be secure since it will only be accessible from time to time (it basically exposes a page temporarily under specific circumstances and takes it offline once the conditions change) – Thomas Kuhlmann Apr 10 '14 at 18:31

2 Answers2

1
after_validation :set_permalink

def rand_permalink #you can find a better way to exclude loop db-searches
  r = rand.to_s[2..8] # 7-digit random, you can make [2..11] for 10-digits and so on
  while find_by_permalink(r).present?
    r = rand.to_s[2..8]
  end
  r      
end 


def set_permalink
  permalink = rand_permalink unless permalink.presence
end
okliv
  • 3,909
  • 30
  • 47
1

Assuming you want to create the unique permalink on create, you want to store it in your database and the class is named Post:

validate :permalink, :uniqueness => true

before_create :create_permalink

private
  def create_permalink
    loop do
      self.permalink = Array(1..7).map{ rand(10).to_s }.join
      return if Posts.where(permalink: permalink).blank?
    end
  end
spickermann
  • 100,941
  • 9
  • 101
  • 131