From 48368924c11429736b6728e7e2aaf41bd62e4454 Mon Sep 17 00:00:00 2001 From: Oskar Eichler Date: Mon, 31 Aug 2026 00:45:20 +0200 Subject: [PATCH] Allow clearing one cached source file --- lib/method_source.rb | 13 +++++++++---- spec/method_source_spec.rb | 30 ++++++++++++++++++++++++++++++ 2 files changed, 39 insertions(+), 4 deletions(-) diff --git a/lib/method_source.rb b/lib/method_source.rb index ffd79ad..660c958 100644 --- a/lib/method_source.rb +++ b/lib/method_source.rb @@ -55,9 +55,15 @@ def self.lines_for(file_name, name=nil) raise SourceNotFoundError, "Could not load source for #{name}: #{e.message}" end - # Clear cache. - def self.clear_cache - @lines_for_file = {} + # Clear cached source lines. + # + # @param [String, nil] file_name The file to evict, or nil to clear all files. + def self.clear_cache(file_name=nil) + if file_name + @lines_for_file.delete(file_name) if @lines_for_file + else + @lines_for_file = {} + end end # @deprecated — use MethodSource::CodeHelpers#complete_expression? @@ -174,4 +180,3 @@ class Proc include MethodSource::SourceLocation::ProcExtensions include MethodSource::MethodExtensions end - diff --git a/spec/method_source_spec.rb b/spec/method_source_spec.rb index 1927670..2f2108c 100644 --- a/spec/method_source_spec.rb +++ b/spec/method_source_spec.rb @@ -1,7 +1,37 @@ require 'spec_helper' +require 'tempfile' describe MethodSource do + describe ".clear_cache" do + it "can evict one file without clearing other cached files" do + first = Tempfile.new("method-source-first") + second = Tempfile.new("method-source-second") + + first.write("first old\n") + second.write("second old\n") + first.flush + second.flush + + expect(MethodSource.lines_for(first.path)).to eq(["first old\n"]) + expect(MethodSource.lines_for(second.path)).to eq(["second old\n"]) + + File.write(first.path, "first new\n") + File.write(second.path, "second new\n") + MethodSource.clear_cache(first.path) + + expect(MethodSource.lines_for(first.path)).to eq(["first new\n"]) + expect(MethodSource.lines_for(second.path)).to eq(["second old\n"]) + + MethodSource.clear_cache + expect(MethodSource.lines_for(second.path)).to eq(["second new\n"]) + ensure + MethodSource.clear_cache + first.close! + second.close! + end + end + describe "source_location (testing 1.8 implementation)" do it 'should return correct source_location for a method' do expect(method(:hello).source_location.first).to match(/spec_helper/)