Class: Java::NetSfEhcache::Cache

Inherits:
Object
  • Object
show all
Includes:
Enumerable
Defined in:
lib/ehcache/cache.rb

Overview

Enhance net.sf.ehcache.Cache with a more Rubyesque API.

Instance Method Summary collapse

Instance Method Details

#[](key) ⇒ Object

Gets an element value from the cache. Unlike the #get method, this method returns the element value, not the Element object.



22
23
24
25
# File 'lib/ehcache/cache.rb', line 22

def [](key)
  element = self.get(key)
  element ? element.value : nil
end

#compare_and_swap(key, &block) ⇒ Object Also known as: update

Atomic compare and swap for cache elements. Invokes the given block with the current value of the element and attempts to replace it with the value returned from the block, repeating until replace returns true. Note that the provided block works only with element values, not Element objects: the result of element.getValue is passed to the block parameter, and the block is expected to return a value based on it. If there is no element with the given key, returns immediately without retrying.



65
66
67
68
69
70
71
# File 'lib/ehcache/cache.rb', line 65

def compare_and_swap(key, &block)
  begin
    old_element = self.get(key)
    return nil unless old_element
    new_element = Ehcache::Element.new(key, yield(old_element.value))
  end until replace(old_element, new_element)
end

#eachObject

Yield each Element stored in this cache to the given block. This method uses Cache#getKeys as its basis, and therefore it is possible that some of the yielded elements have expired.



8
9
10
11
12
# File 'lib/ehcache/cache.rb', line 8

def each
  for key in self.getKeys
    yield self.get(key)
  end
end

#ehcache_putObject



27
# File 'lib/ehcache/cache.rb', line 27

alias ehcache_put put

#marshal?Boolean

Does this cache require marshalling of Ruby objects?

Returns:

  • (Boolean)


15
16
17
18
# File 'lib/ehcache/cache.rb', line 15

def marshal?
  config = self.cache_configuration
  config.overflow_to_disk? || config.overflow_to_off_heap? || config.terracotta_clustered?
end

#put(*args) ⇒ Object Also known as: []=

Wrap the Cache#put method to allow for extra options to be passed to the created Element.



31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
# File 'lib/ehcache/cache.rb', line 31

def put(*args)
  options = args.extract_options!
  if args.size == 1 && args.first.kind_of?(Ehcache::Element)
    element = args.first
  elsif args.size == 2
    if marshal?
      value = Java::NetSfEhcache::MarshaledRubyObject.new(Marshal.dump(args[1]).to_java_bytes)
    end
    element = Ehcache::Element.create(args[0], value, options)
  else
    raise ArgumentError, "Must be Element object or key and value arguments"
  end

  if options[:unless_exist] || options[:unlessExist] ||
     options[:if_absent]    ||options[:ifAbsent]
    put_if_absent(element)
  else
    ehcache_put(element)
  end
end