Class: Zabbirc::IdShortener

Inherits:
Object
  • Object
show all
Defined in:
lib/zabbirc/id_shortener.rb

Defined Under Namespace

Classes: IdTranslation

Constant Summary collapse

CHAR_SET =
("A".."Z").to_a + (2..9).to_a.collect(&:to_s)

Instance Method Summary collapse

Constructor Details

#initialize(max_cache_size = 10_000, shorten_id_length = 3) ⇒ IdShortener

Returns a new instance of IdShortener.



11
12
13
14
15
16
17
# File 'lib/zabbirc/id_shortener.rb', line 11

def initialize max_cache_size=10_000, shorten_id_length = 3
  @max_cache_size = max_cache_size
  @shorten_id_length = shorten_id_length
  @mutex = Mutex.new
  @ids = {}
  @shorten_ids = {}
end

Instance Method Details

#cache_sizeObject



43
44
45
# File 'lib/zabbirc/id_shortener.rb', line 43

def cache_size
  @ids.size
end

#get_id(shorten_id) ⇒ Object



19
20
21
22
23
24
25
26
27
28
29
# File 'lib/zabbirc/id_shortener.rb', line 19

def get_id shorten_id
  @mutex.synchronize do
    translation = @shorten_ids[shorten_id.upcase]
    if translation
      translation.touch
      translation.id
    else
      nil
    end
  end
end

#get_shorten_id(id) ⇒ Object



31
32
33
34
35
36
37
38
39
40
41
# File 'lib/zabbirc/id_shortener.rb', line 31

def get_shorten_id id
  @mutex.synchronize do
    translation = @ids[id]
    return translation.shorten_id if translation
    begin
      shorten_id = generate_shorten_id
    end while @shorten_ids.key?(shorten_id)
    translation = register_translation id, shorten_id
    translation.shorten_id.upcase
  end
end