如何从erubis文件中获取变量名称列表?

时间:2013-02-07 17:55:35

标签: ruby erubis

在Ruby脚本中,有没有办法实用地获取erubis文件中找到的所有预期变量名和函数名的列表?

例如,如何从Eruby对象中确定包含变量'name'?

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

1 个答案:

答案 0 :(得分:0)

我的解决方案:

# 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

结果是:

Found: 'name'