Class: Picky::Backends::File::JSON

Inherits:
Basic show all
Defined in:
lib/picky/backends/file/json.rb

Overview

File-based index files dumped in the JSON format.

Instance Attribute Summary collapse

Attributes inherited from Basic

#cache_path, #mapping_file

Instance Method Summary collapse

Methods inherited from Basic

#delete, #empty, #initial, #initialize, #to_s

Constructor Details

This class inherits a constructor from Picky::Backends::File::Basic

Instance Attribute Details

#mappingObject

The in-memory mapping hash, mapping a Symbol key to [length, offset] of the JSON data in the file.



21
22
23
# File 'lib/picky/backends/file/json.rb', line 21

def mapping
  @mapping || raise("The File index/category needs to be loaded first.")
end

Instance Method Details

#[](key) ⇒ Object

See lib/picky/backends/file.rb for what this should return.

  1. Gets the length and offset for the key.

  2. Extracts and decodes the object from the file.



30
31
32
33
34
35
# File 'lib/picky/backends/file/json.rb', line 30

def [] key
  length, offset = mapping[key]
  return unless length
  result = MultiJson.decode IO.read(cache_path, length, offset)
  result
end

#clearObject

Clears the currently loaded index.

Note: This only clears the in-memory mapping,

but this is enough for the index to not exist
anymore, at least to the application.


43
44
45
# File 'lib/picky/backends/file/json.rb', line 43

def clear
  self.mapping.clear
end

#dump(hash) ⇒ Object

Dumps the index hash in json format.

  1. Dump actual data.

  2. Dumps mapping key => [length, offset].



65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
# File 'lib/picky/backends/file/json.rb', line 65

def dump hash
  offset = 0
  mapping = Hash.new
  
  create_directory cache_path
  ::File.open(cache_path, 'w:utf-8') do |out_file|
    hash.each do |(key, object)|
      encoded = MultiJson.encode object
      length  = encoded.size
      mapping[key] = [length, offset]
      offset += length
      out_file.write encoded
    end
  end

  mapping_file.dump mapping
end

#extensionObject

Uses the extension “json”.



91
92
93
# File 'lib/picky/backends/file/json.rb', line 91

def extension
  :json
end

#load(symbol_keys) ⇒ Object

Loads the mapping hash from json format.



55
56
57
58
# File 'lib/picky/backends/file/json.rb', line 55

def load symbol_keys
  self.mapping = mapping_file.load symbol_keys
  self
end

#retrieveObject

A json file does not provide retrieve functionality.



85
86
87
# File 'lib/picky/backends/file/json.rb', line 85

def retrieve
  raise "Can't retrieve from JSON file. Use text file."
end

#sizeObject

Size of the index is equal to the mapping size.



49
50
51
# File 'lib/picky/backends/file/json.rb', line 49

def size
  self.mapping.size
end