Class: LargeObjectStore::RailsWrapper

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(store) ⇒ RailsWrapper

Returns a new instance of RailsWrapper.



24
25
26
# File 'lib/large_object_store.rb', line 24

def initialize(store)
  @store = store
end

Instance Attribute Details

#storeObject (readonly)

Returns the value of attribute store.



22
23
24
# File 'lib/large_object_store.rb', line 22

def store
  @store
end

Instance Method Details

#delete(key) ⇒ Object



87
88
89
# File 'lib/large_object_store.rb', line 87

def delete(key)
  @store.delete(key(key, 0))
end

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



79
80
81
82
83
84
85
# File 'lib/large_object_store.rb', line 79

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

#read(key) ⇒ Object



59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
# File 'lib/large_object_store.rb', line 59

def read(key)
  # read pages
  pages, uuid = @store.read(key(key, 0))
  return if pages.nil?

  data = if pages.is_a?(Fixnum)
    # read sliced data
    keys = Array.new(pages).each_with_index.map{|_,i| key(key, i+1) }
    slices = @store.read_multi(*keys).values
    return nil if slices.compact.size != pages
    slices.map! { |s| [s.slice!(0, UUID_SIZE), s] }
    return nil unless slices.map(&:first).uniq == [uuid]
    slices.map!(&:last).join("")
  else
    pages
  end

  deserialize(data)
end

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



28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
# File 'lib/large_object_store.rb', line 28

def write(key, value, options = {})
  options = options.dup
  value = serialize(value, options)

  # calculate slice size; note that key length is a factor because
  # the key is stored on the same slab page as the value
  slice_size = MAX_OBJECT_SIZE - ITEM_HEADER_SIZE - UUID_SIZE - key.bytesize

  # store number of pages
  pages = (value.size / slice_size.to_f).ceil

  if pages == 1
    !!@store.write(key(key, 0), value, options)
  else
    # store meta
    uuid = SecureRandom.hex(UUID_BYTES)
    return false unless @store.write(key(key, 0), [pages, uuid], options) # invalidates the old cache

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

      return false unless @store.write(key(key, page), slice.prepend(uuid), options.merge(raw: true))
      page += 1
    end
    true
  end
end