Skip to content
This repository
tag: v4.5.6
Fetching contributors…

Cannot retrieve contributors at this time

file 97 lines (79 sloc) 2.325 kb
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 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 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97
module Picky

  module Backends

    class File

      # File-based index files dumped in the JSON format.
      #
      class JSON < Basic

        attr_writer :mapping

        # The in-memory mapping hash, mapping
        # a Symbol key to [length, offset] of
        # the JSON data in the file.
        #
        def mapping
          @mapping || raise("The File index/category needs to be loaded first.")
        end

        # 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.
        #
        def [] key
          length, offset = mapping[key]
          return unless length
          result = MultiJson.decode IO.read(cache_path, length, offset)
          result
        end

        # 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.
        #
        def clear
          self.mapping.clear
        end

        # Size of the index is equal to the mapping size.
        #
        def size
          self.mapping.size
        end

        # Loads the mapping hash from json format.
        #
        def load
          self.mapping = mapping_file.load
          self
        end

        # Dumps the index hash in json format.
        #
        # 1. Dump actual data.
        # 2. Dumps mapping key => [length, offset].
        #
        def dump hash
          offset = 0
          mapping = {}

          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

        # A json file does not provide retrieve functionality.
        #
        def retrieve
          raise "Can't retrieve from JSON file. Use text file."
        end

        # Uses the extension "json".
        #
        def extension
          :json
        end

      end

    end

  end

end
Something went wrong with that request. Please try again.