Sha256: ab3f471371e8f7b2e4eb0caa5818e3da88867637e17916675423877d4d323a0f

Contents?: true

Size: 1.7 KB

Versions: 1

Compression:

Stored size: 1.7 KB

Contents

# frozen_string_literal: true

class StringBase
  SHORT_KEYS   ||= 'bcdghjklmnpqrstvwxyz'
  MDEIUM_KEYS  ||= 'abcdefghijklmnopqrstuvwxyz0123456789'
  LONG_KEYS    ||= 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'

  class << self
    def encode text
      short.encode text
    end

    def decode text
      short.decode text
    end

    def short
      new(keys: SHORT_KEYS, multiplier: 99)
    end

    def medium
      new(keys: MDEIUM_KEYS)
    end

    def long
      new(keys: LONG_KEYS)
    end

    def uid
      [
        Time.now.to_f,
        rand.to_s.sub('0.',''),
      ].join('').to_s.sub('.','').to_i.to_s(36)[0, 16]
    end
  end

  ###

  def initialize keys: nil, multiplier: 1
    @keys = keys
    @multiplier = multiplier
  end

  def encode value
    value = value * @multiplier
    ring = Hash[@keys.chars.map.with_index.to_a.map(&:reverse)]
    base = @keys.length
    result = []
    until value == 0
      result << ring[ value % base ]
      value /= base
    end
    result.reverse.join
  end

  def decode string
    ring = Hash[@keys.chars.map.with_index.to_a]
    base = @keys.length
    ret = string.reverse.chars.map.with_index.inject(0) do |sum, (char, i)|
      sum + ring[char] * (base**i)
    end
    raise 'Invalid decode base' if ret % @multiplier > 0
    ret / @multiplier
  end

  # extract ID from url
  def extract url_part
    id_str = url_part.split('-').last
    return nil unless id_str
    StringBase.decode(id_str) rescue nil
  end
end

class Integer
  def string_id
    StringBase.encode self
  end
end

class String
  def string_id
    begin
      StringBase.decode self.split('-').last
    rescue
      raise ArgumentError.new('Bad ID for string_id')
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
lux-fw-0.6.2 ./lib/common/string_base.rb