- by JP
While its not my application a simple way to explain my problem is to assume I'm running a URL shortener. Rather than attempt to try and figure out what the next string I should use as the unique section of the URL, I just index all my URLs by integer and map the numbers to strings behind the scenes, essentially just changing the base of the number to, let's say, 62: a-z + A-Z + 0-9.
In ActiveRecord I can easily alter the reader for the url_id field so that it returns my base 62 string instead of the number being stored in the database:
class Short < ActiveRecord::Base
def url_id
i = read_attribute(:convo)
return '0' if i == 0
s = ''
while i > 0
s << CHARS[i.modulo(62)]
i /= 62
end
s
end
end
but is there a way to tell ActiveRecord to accept Short.find(:first,:conditions=>{:url_id=>'Ab7'}), ie. putting the 'decoding' logic into my Short ActiveRecord class?
I guess I could define my own def self.find_by_unique_string(string), but that feels like cheating somehow! Thanks!