Class: Cache::LinkedList

Inherits:
Object
  • Object
show all
Defined in:
lib/background_queue/server_lib/lru.rb

Defined Under Namespace

Classes: Element

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeLinkedList

Returns a new instance of LinkedList.



124
125
126
# File 'lib/background_queue/server_lib/lru.rb', line 124

def initialize
  @head = @last = nil
end

Instance Attribute Details

#lastObject (readonly)

Returns the value of attribute last.



123
124
125
# File 'lib/background_queue/server_lib/lru.rb', line 123

def last
  @last
end

Instance Method Details

#add(key, value) ⇒ Object



128
129
130
# File 'lib/background_queue/server_lib/lru.rb', line 128

def add(key, value)
  add_element(Element.new(key, value, @head))
end

#add_element(el) ⇒ Object



132
133
134
135
136
137
138
139
140
# File 'lib/background_queue/server_lib/lru.rb', line 132

def add_element(el)
  @head.previous_element = el if @head

  el.next_element = @head
  el.previous_element = nil
  @head = el
  @last = el unless @last
  el
end

#move_to_head(el) ⇒ Object



150
151
152
153
# File 'lib/background_queue/server_lib/lru.rb', line 150

def move_to_head(el)
  remove_element(el)
  add_element(el)
end

#ppObject

Returns a nicely formatted stirng of all elements in the linked list. First element is most recently used, last element is least recently used.



158
159
160
161
162
163
164
165
166
167
# File 'lib/background_queue/server_lib/lru.rb', line 158

def pp
  s = ''
  el = @head
  while el
    s << ', ' if s.size > 0
    s <<  el.to_s
    el = el.next_element
  end
  s
end

#remove_element(el) ⇒ Object



142
143
144
145
146
147
148
# File 'lib/background_queue/server_lib/lru.rb', line 142

def remove_element(el)
  el.previous_element.next_element = el.next_element if el.previous_element
  el.next_element.previous_element = el.previous_element if el.next_element

  @last = el.previous_element if el == @last
  @head = el.next_element if el == @head
end