Class: Attractor::CacheAdapter::JSON

Inherits:
Base
  • Object
show all
Defined in:
lib/attractor/cache.rb

Instance Method Summary collapse

Constructor Details

#initializeJSON

Returns a new instance of JSON.



39
40
41
42
43
44
45
46
47
48
49
50
51
# File 'lib/attractor/cache.rb', line 39

def initialize
  super

  @data_directory = "tmp"
  FileUtils.mkdir_p @data_directory
  FileUtils.touch filename

  begin
    @store = ::JSON.parse(File.read(filename))
  rescue ::JSON::ParserError
    @store = {}
  end
end

Instance Method Details

#clearObject



73
74
75
# File 'lib/attractor/cache.rb', line 73

def clear
  FileUtils.rm filename
end

#filenameObject



77
78
79
# File 'lib/attractor/cache.rb', line 77

def filename
  "#{@data_directory}/attractor-cache.json"
end

#persist!Object



69
70
71
# File 'lib/attractor/cache.rb', line 69

def persist!
  File.write(filename, ::JSON.dump(@store))
end

#read(file_path:) ⇒ Object



53
54
55
56
57
58
59
60
# File 'lib/attractor/cache.rb', line 53

def read(file_path:)
  value_hash = @store[file_path]

  Value.new(**value_hash.values.first.transform_keys(&:to_sym)) unless value_hash.nil?
rescue ArgumentError => e
  puts "Couldn't rehydrate value from cache: #{e.message}"
  nil
end

#write(file_path:, value:) ⇒ Object



62
63
64
65
66
67
# File 'lib/attractor/cache.rb', line 62

def write(file_path:, value:)
  mappings = {x: :churn, y: :complexity}

  transformed_value = value.to_h.transform_keys { |k| mappings[k] || k }
  @store[file_path] = {value.current_commit => transformed_value}
end