Class: StringBase
Class Method Summary collapse
- .decode(text) ⇒ Object
- .encode(text) ⇒ Object
- .long ⇒ Object
- .medium ⇒ Object
- .short ⇒ Object
- .uid ⇒ Object
Instance Method Summary collapse
- #decode(string) ⇒ Object
- #encode(value) ⇒ Object
-
#extract(url_part) ⇒ Object
extract ID from url.
-
#initialize(keys: nil, multiplier: 1) ⇒ StringBase
constructor
A new instance of StringBase.
Constructor Details
#initialize(keys: nil, multiplier: 1) ⇒ StringBase
Returns a new instance of StringBase.
39 40 41 42 |
# File 'lib/common/string_base.rb', line 39 def initialize keys: nil, multiplier: 1 @keys = keys @multiplier = multiplier end |
Class Method Details
.decode(text) ⇒ Object
13 14 15 |
# File 'lib/common/string_base.rb', line 13 def decode text short.decode text end |
.encode(text) ⇒ Object
9 10 11 |
# File 'lib/common/string_base.rb', line 9 def encode text short.encode text end |
.long ⇒ Object
25 26 27 |
# File 'lib/common/string_base.rb', line 25 def long new(keys: LONG_KEYS) end |
.medium ⇒ Object
21 22 23 |
# File 'lib/common/string_base.rb', line 21 def medium new(keys: MDEIUM_KEYS) end |
.short ⇒ Object
17 18 19 |
# File 'lib/common/string_base.rb', line 17 def short new(keys: SHORT_KEYS, multiplier: 99) end |
.uid ⇒ Object
29 30 31 32 33 34 |
# File 'lib/common/string_base.rb', line 29 def uid [ Time.now.to_f, rand.to_s.sub('0.',''), ].join('').to_s.sub('.','').to_i.to_s(36)[0, 16] end |
Instance Method Details
#decode(string) ⇒ Object
56 57 58 59 60 61 62 63 64 |
# File 'lib/common/string_base.rb', line 56 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 |
#encode(value) ⇒ Object
44 45 46 47 48 49 50 51 52 53 54 |
# File 'lib/common/string_base.rb', line 44 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 |
#extract(url_part) ⇒ Object
extract ID from url
67 68 69 70 71 |
# File 'lib/common/string_base.rb', line 67 def extract url_part id_str = url_part.split('-').last return nil unless id_str StringBase.decode(id_str) rescue nil end |