class Measured::Cache::Json

Attributes

filename[R]
path[R]

Public Class Methods

new(filename) click to toggle source
# File lib/measured/cache/json.rb, line 6
def initialize(filename)
  @filename = filename
  @path = Pathname.new(File.join(File.dirname(__FILE__), "../../../cache", @filename)).cleanpath
end

Public Instance Methods

exist?() click to toggle source
# File lib/measured/cache/json.rb, line 11
def exist?
  File.exist?(@path)
end
read() click to toggle source
# File lib/measured/cache/json.rb, line 15
def read
  return unless exist?
  decode(JSON.load(File.read(@path), nil, freeze: true))
end
write(table) click to toggle source
# File lib/measured/cache/json.rb, line 20
def write(table)
  raise ArgumentError, "Cannot overwrite file cache at runtime."
end

Private Instance Methods

decode(table) click to toggle source
# File lib/measured/cache/json.rb, line 39
def decode(table)
  table.transform_values do |value1|
    if value1.is_a?(Hash)
      value1.transform_values do |value2|
        if value2.is_a?(Hash)
          Rational(value2["numerator"], value2["denominator"])
        else
          value2
        end
      end
    else
      value1
    end
  end
end
encode(table) click to toggle source

JSON dump and load of Rational objects exists, but it changes the behaviour of JSON globally if required. Instead, the same marshalling technique is rewritten here to prevent changing this behaviour project wide. github.com/ruby/ruby/blob/trunk/ext/json/lib/json/add/rational.rb

# File lib/measured/cache/json.rb, line 29
def encode(table)
  table.each_with_object(table.dup) do |(k1, v1), accu|
    v1.each do |k2, v2|
      if v2.is_a?(Rational)
        accu[k1][k2] = { "numerator" => v2.numerator, "denominator" => v2.denominator }
      end
    end
  end
end