Class: MiniSql::Abstract::PreparedCache

Inherits:
Object
  • Object
show all
Defined in:
lib/mini_sql/abstract/prepared_cache.rb

Constant Summary collapse

DEFAULT_MAX_SIZE =
500

Instance Method Summary collapse

Constructor Details

#initialize(connection, max_size = nil) ⇒ PreparedCache

Returns a new instance of PreparedCache.



9
10
11
12
13
14
# File 'lib/mini_sql/abstract/prepared_cache.rb', line 9

def initialize(connection, max_size = nil)
  @connection = connection
  @max_size = max_size || DEFAULT_MAX_SIZE
  @cache = {}
  @counter = 0
end

Instance Method Details

#prepare_statement(sql) ⇒ Object



16
17
18
19
20
21
22
23
24
25
26
27
# File 'lib/mini_sql/abstract/prepared_cache.rb', line 16

def prepare_statement(sql)
  stm_key = "#{@connection.object_id}-#{sql}"
  statement = @cache.delete(stm_key)
  if statement
    @cache[stm_key] = statement
  else
    statement = @cache[stm_key] = alloc(sql)
    dealloc(@cache.shift.last) if @cache.length > @max_size
  end

  statement
end