Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on Jun 12th, 2012  |  syntax: None  |  size: 1.23 KB  |  hits: 16  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. how to implement a short url like urls in twitter?
  2. 12341235.to_s(36)
  3. #=> "7cik3"
  4.  
  5. "7cik3".to_i(36)
  6. #=> 12341235
  7.        
  8. module AnyBase
  9.   ENCODER = Hash.new do |h,k|
  10.     h[k] = Hash[ k.chars.map.with_index.to_a.map(&:reverse) ]
  11.   end
  12.   DECODER = Hash.new do |h,k|
  13.     h[k] = Hash[ k.chars.map.with_index.to_a ]
  14.   end
  15.   def self.encode( value, keys )
  16.     ring = ENCODER[keys]
  17.     base = keys.length
  18.     result = []
  19.     until value == 0
  20.       result << ring[ value % base ]
  21.       value /= base
  22.     end
  23.     result.reverse.join
  24.   end
  25.   def self.decode( string, keys )
  26.     ring = DECODER[keys]
  27.     base = keys.length
  28.     string.reverse.chars.with_index.inject(0) do |sum,(char,i)|
  29.       sum + ring[char] * base**i
  30.     end
  31.   end
  32. end
  33.        
  34. base36 = "0123456789abcdefghijklmnopqrstuvwxyz"
  35. db_id = 12341235
  36. p AnyBase.encode( db_id, base36 )
  37. #=> "7cik3"
  38. p AnyBase.decode( "7cik3", base36 )
  39. #=> 12341235
  40.  
  41. base62 = [ *0..9, *'a'..'z', *'A'..'Z' ].join
  42. p AnyBase.encode( db_id, base62 )
  43. #=> "PMwb"
  44. p AnyBase.decode( "PMwb", base62 )
  45. #=> 12341235
  46.        
  47. gem install bitly
  48.  
  49. # Use api version 3 or get a deprecation warning
  50. Bitly.use_api_version_3
  51.  
  52. # Create a client
  53. bitly = Bitly.new(username, api_key)
  54.  
  55. # Call method shorten
  56. bitly.shorten('http://www.google.com').short_url