-1

If I have a file model.rb:

require 'foo.rb'
require 'foo/bar.rb'

class Model
  def self.foo
    Foo.new
  end

  def bar
    Foo::Bar.to_s
  end

  Foo::Bar::Baz.class_does_not_exist
end

How could I parse this file to return valid class references? For instance, if Foo and Foo::Bar are defined elsewhere, but Foo::Bar::Baz is not, then I would want something like:

parse_for_valid_class_references(File.open('model.rb', 'rb'))
# => [Foo, Foo::Bar]
stevenspiel
  • 5,775
  • 13
  • 60
  • 89

1 Answers1

0

One way to do it would be to execute a shell script that runs a separate ruby process, requires the file, checks what constants are added, and prints it.

if you have file 1.rb:

class Foo; end

then you can write this ruby code elsewhere:

require 'json'
def constants_added_by_file(path)
  cmd = <<-RB
    require 'json'
    consts = Object.constants
    require '#{path}'
    puts((Object.constants - consts).to_json)
  RB
  JSON.parse `ruby -e "#{cmd}"`
end

puts constants_added_by_file('./1.rb')
# => Foo
max pleaner
  • 26,189
  • 9
  • 66
  • 118