Module: UrlKeyedObject

Defined in:
lib/url_keyed_object.rb,
lib/url_keyed_object/railtie.rb,
lib/url_keyed_object/active_record.rb,
lib/url_keyed_object/rspec/matchers.rb

Defined Under Namespace

Modules: ActiveRecord, RSpec Classes: Railtie

Class Method Summary collapse

Class Method Details

.decode_url_key(url_key) ⇒ Object

decode a moderately dirty URL key



37
38
39
# File 'lib/url_keyed_object.rb', line 37

def decode_url_key(url_key)
  url_key.downcase.tr('o', '0').tr('il', '1')
end

.decode_well_formed_url_key(url_key, length = 5) ⇒ Object

decode and validate a key, returning the decoded key only if it’s well-formed



42
43
44
45
# File 'lib/url_keyed_object.rb', line 42

def decode_well_formed_url_key(url_key, length = 5)
  decoded_url_key = decode_url_key(url_key)
  well_formed_url_key?(decoded_url_key, length) ? decoded_url_key : nil
end

.generate_checked_url_key(length = 5) ⇒ Object

Keeps generating new URL keys until the passed-in block returns true



23
24
25
26
27
28
29
# File 'lib/url_keyed_object.rb', line 23

def generate_checked_url_key(length = 5)
  key = generate_unchecked_url_key(length)
  while !yield(key)
    key = generate_unchecked_url_key(length)
  end
  key
end

.generate_unchecked_url_key(length = 5) ⇒ Object

generates a url key from a random 5-digit base 31 number, without checking its uniqueness



16
17
18
19
20
# File 'lib/url_keyed_object.rb', line 16

def generate_unchecked_url_key(length = 5)
  (1..length).collect do
    key_encoding[rand(31)]
  end.join('')
end

.key_encodingObject

holds an array so a base-31 column (units / tens / hundreds) equiv can be encoded as an ASCII character



8
9
10
11
12
13
# File 'lib/url_keyed_object.rb', line 8

def key_encoding
  @key_encoding ||= ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", 
                     "a", "b", "c", "d", "e", "f", "g", "h", "j", "k", 
                     "m", "n", "p", "q", "r", "s", "v", "w", "x", "y", 
                     "z"]
end

.well_formed_url_key?(url_key, length = 5) ⇒ Boolean

Validate the well-formedness of a URL key

Returns:

  • (Boolean)


32
33
34
# File 'lib/url_keyed_object.rb', line 32

def well_formed_url_key?(url_key, length = 5)
  !url_key.match(Regexp.new("^[0-9abcdefghjkmnpqrsvwxyz]{#{length.to_i}}$")).nil?
end