Class: LargeObjectStore::RailsWrapper

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

Constant Summary collapse

LIMIT =
1024**2 - 100

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(store) ⇒ RailsWrapper

Returns a new instance of RailsWrapper.



14
15
16
# File 'lib/large_object_store.rb', line 14

def initialize(store)
  @store = store
end

Instance Attribute Details

#storeObject (readonly)

Returns the value of attribute store.



10
11
12
# File 'lib/large_object_store.rb', line 10

def store
  @store
end

Instance Method Details

#fetch(key, options = {}) ⇒ Object



59
60
61
62
63
64
65
# File 'lib/large_object_store.rb', line 59

def fetch(key, options={})
  value = read(key)
  return value unless value.nil?
  value = yield
  write(key, value, options)
  value
end

#read(key) ⇒ Object



42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
# File 'lib/large_object_store.rb', line 42

def read(key)
  # read pages
  pages = @store.read("#{key}_0")
  return if pages.nil?

  data = if pages.is_a?(String)
    pages
  else
    # read sliced data
    keys = Array.new(pages).each_with_index.map{|_,i| "#{key}_#{i+1}" }
    slices = @store.read_multi(*keys).values
    return nil if slices.compact.size < pages
    slices.join("")
  end
  Marshal.load(data)
end

#write(key, value, options = {}) ⇒ Object



18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
# File 'lib/large_object_store.rb', line 18

def write(key, value, options = {})
  value = Marshal.dump(value)
  
  # store number of pages
  pages = (value.size / LIMIT.to_f).ceil

  if pages == 1
    @store.write("#{key}_0", value, options)
  else
    @store.write("#{key}_0", pages, options)

    # store object
    page = 1
    loop do
      slice = value.slice!(0, LIMIT)
      break if slice.size == 0

      @store.write("#{key}_#{page}", slice, options)
      page += 1
    end
  end
  true
end