rubyerubis

How to get list of variable names from an erubis file?


From within a Ruby script, is there a way to pragmatically obtain a list of all expected variable names and function names found in an erubis file?

For instance, how would one determine from the Eruby object that the contains the variable 'name'?

require 'erubis'
source = 'Hello, <%= name %>'
erb = Erubis::Eruby.new(source)

Solution

  • My hackish solution:

    # from the original question
    require 'erubis'
    source = 'Hello, <%= name %>'
    erb = Erubis::Eruby.new(source)
    
    # a not so great solution
    vars = {}
    begin
      Erubis::Eruby.new(code).result(vars)
    rescue NameError => e
      puts "Found: '#{e.name}'"
      vars[e.name.to_sym] = nil
      retry
    end
    

    Which results in:

    Found: 'name'