Skip to content

Instantly share code, notes, and snippets.

@takkkun
Last active December 16, 2015 08:19
Show Gist options
  • Select an option

  • Save takkkun/5404690 to your computer and use it in GitHub Desktop.

Select an option

Save takkkun/5404690 to your computer and use it in GitHub Desktop.
constants = []
current_expr = nil
set_trace_func lambda { |event, file, line, id, binding, klass|
if current_expr
e, b = current_expr
if b.eval("defined? #{e}") == 'constant'
const = b.eval(e)
constants << const unless constants.include?(const)
end
current_expr = nil
end
case event
when 'class'
const = binding.eval('self')
constants << const unless constants.include?(const)
when 'c-return'
if (klass == Module || klass == Class) && id == :new
expr = File.open(file, 'r') { |f| f.each_line.take(line) }.last.strip
begin
if binding.eval("defined? #{expr}") == 'assignment'
left_expr = expr.split('=', 2)[0].strip
current_expr = [left_expr, binding]
end
rescue SyntaxError
end
elsif klass == Module && id == :const_set
expr = File.open(file, 'r') { |f| f.each_line.take(line) }.last.strip
left_expr, right_expr = expr.split('const_set', 2).map(&:strip)
left_expr.chomp!('.')
left_expr = 'self' if left_expr.empty?
_, right_expr = /:([^,]+),/.match(right_expr).to_a
current_expr = ["#{left_expr}::#{right_expr}", binding]
end
end
}
class Neko
end
class Neko
module Mike
end
const_set :Tama, Module.new
end
Neko.const_set(:Poyo, Class.new)
Inu = Class.new
Usagi = Module.new # これ以降に何かしらの呼び出しがないとset_trace_funcが呼ばれないので、Usagiだけ取れない、とかもアリ
a = Class.new
p constants
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment