Sha256: 2ffa4de8d7246a57c848147e83089316de57bf63e90cc11b71d16a1d0204900c

Contents?: true

Size: 1.69 KB

Versions: 2

Compression:

Stored size: 1.69 KB

Contents

require "active_support/concern"
require "obfuscated_identifier/version"

module ObfuscatedIdentifier
  extend ActiveSupport::Concern

  def to_param
    to_identifier
  end

  def to_identifier
    self.class.to_identifier(id)
  end

  module ClassMethods
    attr_reader :identifier_length

    def obfusicate_identifier(pattern, offset, length = 16)
      @identifier_pattern = pattern
      @identifier_offset = offset
      @identifier_length = 16
    end

    def generate_identifier_pattern
      %w{0 1 2 3 4 5 6 7 8 9 a b c d e}.shuffle
    end

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

    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

    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

    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

    protected

    def pad_number(value)
      sprintf("%0#{@identifier_length}d", value)
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
obfuscated_identifier-1.0.0 lib/obfuscated_identifier.rb
obfuscated_identifier-0.0.3 lib/obfuscated_identifier.rb