Skip to content

Instantly share code, notes, and snippets.

@jweir
Last active May 2, 2023 21:09
Show Gist options
  • Save jweir/525f5a9673c713350c06 to your computer and use it in GitHub Desktop.
Save jweir/525f5a9673c713350c06 to your computer and use it in GitHub Desktop.
Simple parse to find all constants in a Ruby file
require 'test_helper'
require 'ripper'
# see http://svenfuchs.com/2009/7/5/using-ruby-1-9-ripper
# Only finds contants which are referenced or defined via class
# does not find constants which are defined inline i.e. X=true
class ConstParser < Struct.new(:source)
def consts
consts = []
walker = -> x do
x.each do |token, *remainder|
# Will not find classed defined like X = Struct.new do; end
if token == :const_path_ref || token == :const_ref
# cheating here and just getting the string portion,
# this might be a bit fragile
consts << remainder.flatten.select {|p| p.is_a?(String)}.join("::")
else
walker.call(remainder) if remainder.is_a?(Array)
walker.call(token) if token.is_a?(Array)
end
end
end
walker.call(Ripper.sexp(File.read(source)))
consts
end
end
describe ConstParser do
let(:p) { ConstParser.new 'app/schedules/pjm/dispatch_lambda_job.rb' }
it { assert_equal [], p.consts }
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment