Sha256: 0c5fafd5f2dee222c53e00c04bef86e3f128ba926a13a0b616c164171e661360

Contents?: true

Size: 1.2 KB

Versions: 114

Compression:

Stored size: 1.2 KB

Contents

require 'securerandom'

module Tins
  class Token < String
    DEFAULT_ALPHABET =
      "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ".freeze

    BASE64_ALPHABET =
      "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".freeze

    BASE64_URL_FILENAME_SAFE_ALPHABET =
      "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_".freeze

    BASE32_ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567".freeze

    BASE32_EXTENDED_HEX_ALPHABET = "0123456789ABCDEFGHIJKLMNOPQRSTUV".freeze

    BASE16_ALPHABET = "0123456789ABCDEF".freeze

    def initialize(bits: 128, length: nil, alphabet: DEFAULT_ALPHABET, random: SecureRandom)
      alphabet.size > 1 or raise ArgumentError, 'need at least 2 symbols in alphabet'
      if length
        length > 0 or raise ArgumentError, 'length has to be positive'
      else
        bits > 0 or raise ArgumentError, 'bits has to be positive'
        length = (Math.log(1 << bits) / Math.log(alphabet.size)).ceil
      end
      self.bits = (Math.log(alphabet.size ** length) / Math.log(2)).floor
      token = ''
      length.times { token << alphabet[random.random_number(alphabet.size)] }
      super token
    end

    attr_accessor :bits
  end
end

Version data entries

114 entries across 100 versions & 8 rubygems

Version Path
tins-1.16.2 lib/tins/token.rb
tins-1.16.1 lib/tins/token.rb
tins-1.16.0 lib/tins/token.rb
tins-1.15.1 lib/tins/token.rb
tdiary-5.0.6 vendor/bundle/gems/tins-1.15.0/lib/tins/token.rb
logstash-filter-cache-redis-0.3.1 vendor/bundle/jruby/1.9/gems/tins-1.6.0/lib/tins/token.rb
logstash-filter-cache-redis-0.3.0 vendor/bundle/jruby/1.9/gems/tins-1.6.0/lib/tins/token.rb
logstash-filter-cache-redis-0.2.0 vendor/bundle/jruby/1.9/gems/tins-1.6.0/lib/tins/token.rb
logstash-filter-cache-redis-0.1.0 vendor/bundle/jruby/1.9/gems/tins-1.6.0/lib/tins/token.rb
tins-1.15.0 lib/tins/token.rb
tdiary-5.0.5 vendor/bundle/gems/tins-1.14.0/lib/tins/token.rb
tdiary-5.0.5 vendor/bundle/gems/tins-1.13.2/lib/tins/token.rb
tdiary-5.0.5 vendor/bundle/gems/tdiary-5.0.4/vendor/bundle/gems/tins-1.13.2/lib/tins/token.rb
tins-1.14.0 lib/tins/token.rb
tins-1.13.3 lib/tins/token.rb
enju_leaf-1.2.1 vendor/bundle/ruby/2.3/gems/tins-1.13.2/lib/tins/token.rb
tdiary-5.0.4 vendor/bundle/gems/tins-1.13.2/lib/tins/token.rb
tins-1.13.2 lib/tins/token.rb
ivanvc-logstash-input-s3-3.1.1.4 vendor/local/gems/tins-1.13.0/lib/tins/token.rb
ivanvc-logstash-input-s3-3.1.1.3 vendor/local/gems/tins-1.13.0/lib/tins/token.rb