Module: ObfuscatedIdentifier::ClassMethods

Defined in:
lib/obfuscated_identifier.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Instance Attribute Details

#identifier_lengthObject (readonly)

Returns the value of attribute identifier_length.



16
17
18
# File 'lib/obfuscated_identifier.rb', line 16

def identifier_length
  @identifier_length
end

Instance Method Details

#from_identifier(value) ⇒ Object



33
34
35
36
37
38
39
40
41
42
43
# 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) ⇒ Object



28
29
30
31
# File 'lib/obfuscated_identifier.rb', line 28

def from_param(value)
  id = from_identifier(value)
  find_by_id!(id)
end

#generate_identifier_patternObject



24
25
26
# 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) ⇒ Object



18
19
20
21
22
# 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) ⇒ Object



53
54
55
56
57
58
59
60
61
62
63
# 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) ⇒ Boolean

Returns:

  • (Boolean)


45
46
47
48
49
50
51
# 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