Class: EncodeId
- Inherits:
-
Object
- Object
- EncodeId
- Defined in:
- lib/encode_id.rb
Instance Attribute Summary collapse
-
#grows ⇒ Object
readonly
Returns the value of attribute grows.
-
#max_digits ⇒ Object
readonly
Returns the value of attribute max_digits.
Instance Method Summary collapse
- #decode(c) ⇒ Object
- #encode(id) ⇒ Object
-
#initialize(max_digits = 6, grows = false) ⇒ EncodeId
constructor
A new instance of EncodeId.
- #max_alias ⇒ Object
- #max_id ⇒ Object
Constructor Details
#initialize(max_digits = 6, grows = false) ⇒ EncodeId
Returns a new instance of EncodeId.
6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
# File 'lib/encode_id.rb', line 6 def initialize(max_digits=6, grows=false) @base=[ 'VaRCScev0fNjk9HDGlmTobPq7rIsYtux5yzAgBE4pFihUJnK3LMd1Q6XZ', 'JK3LMNtuvx5yzABCDE4FGHIP1QRSTUV6XYZabcde0fghijk9lmnopq7rs', 'STUV6XYZabcde0fghijk9lmK3LMNnopq7rstuvP1QRx5yzABCDE4FGHIJ', 'P1QRk9lmnopq7rsSTdzABCDEuJK3LMN4FGHe0fghijtvx5yUV6XYZabcI', 'lmnopDE4FGHe0fghijtuJK3LMNvx5q7rsSTdzABCIPyUV6XYZabc1QRk9', 'vx5yzABCDE4FGHUV6XYZk9lmnopq7rsP1QRSTde0fghijtuabcIJK3LMN', 'TdzABCIPyUV6XYZabc1QRk9lmnopDE4FGHe0fghijtuJK3LMNvx5q7rsS', 'QRSTde0fghijtuabcIJK3LMNvx5yzABCDE4FGHUV6XYZk9lmnopq7rsP1', '4FGHe0fghijtP1QRk9lmnopq7rsSTdzABCDEuJK3LMNvx5yUV6XYZabcI', 'q7rsSTdzABCIPyUV6XYZabc1QRk9lmnopDE4FGHe0fghijtuJK3LMNvx5', ] @max_digits = max_digits @grows = grows @base_len = @base.length() @n_base = @base[0].length() end |
Instance Attribute Details
#grows ⇒ Object (readonly)
Returns the value of attribute grows.
4 5 6 |
# File 'lib/encode_id.rb', line 4 def grows @grows end |
#max_digits ⇒ Object (readonly)
Returns the value of attribute max_digits.
3 4 5 |
# File 'lib/encode_id.rb', line 3 def max_digits @max_digits end |
Instance Method Details
#decode(c) ⇒ Object
42 43 44 45 46 47 48 49 50 51 |
# File 'lib/encode_id.rb', line 42 def decode(c) id = 0 x = 1 for bit in 0..c.length() - 1 v = @base[bit % @base_len].index(c[bit]) id += v * x x *= @n_base end return id end |
#encode(id) ⇒ Object
25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 |
# File 'lib/encode_id.rb', line 25 def encode(id) if(!@grows && id > max = self.max_id()) raise "Limit id(#{id}) for #{@max_digits} digits(#{max}) in EncodeId.encode, possible lost of information" end ret = '' aux = id bit = 0 while (@grows && aux) || (@max_digits > bit) do a = aux % @n_base ret.concat(@base[bit % @base_len][a]) aux = (aux - a) / @n_base bit += 1 end return ret end |
#max_alias ⇒ Object
54 55 56 57 58 59 60 |
# File 'lib/encode_id.rb', line 54 def max_alias a = '' for bit in 0..@max_digits a.concat(@base[bit % @base_len][-1]) end return a end |
#max_id ⇒ Object
63 64 65 |
# File 'lib/encode_id.rb', line 63 def max_id() @n_base.pow(@max_digits) end |