module ObfuscatedIdentifier::ClassMethods

Attributes

identifier_length[R]

Public Instance Methods

from_identifier(value) click to toggle source
# File lib/obfuscated_identifier.rb, line 33
def from_identifier(value)
  return nil unless valid_identifier_pattern?(value)

  counts = value.each_char.map { |c| @identifier_pattern.index(c.to_s) }.reverse

  numbers = counts[0..-2].each_with_index.map do |count, index|
    ((count - counts[index + 1]) - @identifier_offset) % @identifier_pattern.length
  end + [(counts[-1] - @identifier_offset) % @identifier_pattern.length]

  numbers.join('').to_i
end
from_param(value) click to toggle source
# File lib/obfuscated_identifier.rb, line 28
def from_param(value)
  id = from_identifier(value)
  find_by_id!(id)
end
generate_identifier_pattern() click to toggle source
# File lib/obfuscated_identifier.rb, line 24
def generate_identifier_pattern
  %w{0 1 2 3 4 5 6 7 8 9 a b c d e}.shuffle
end
obfusicate_identifier(pattern, offset, length = 16) click to toggle source
# File lib/obfuscated_identifier.rb, line 18
def obfusicate_identifier(pattern, offset, length = 16)
  @identifier_pattern = pattern
  @identifier_offset = offset
  @identifier_length = 16
end
to_identifier(value) click to toggle source
# File lib/obfuscated_identifier.rb, line 53
def to_identifier(value)
  padded_string = pad_number(value)

  count = 0
  counts = padded_string.reverse.each_char.map do |c|
    count += (c.to_i + @identifier_offset)
    count = count % @identifier_pattern.length
  end

  counts.map { |c| @identifier_pattern[c] }.join('')
end
valid_identifier_pattern?(value) click to toggle source
# File lib/obfuscated_identifier.rb, line 45
def valid_identifier_pattern?(value)
  return false if value.nil? || value == ''
  return false if value.length != @identifier_length
  return false if value.match(/[^a-f 0-9]/)

  true
end

Protected Instance Methods

pad_number(value) click to toggle source
# File lib/obfuscated_identifier.rb, line 67
def pad_number(value)
  sprintf("%0#{@identifier_length}d", value)
end