Ruby erb为main:Object(NameError)提供未定义的局部变量或方法
erb为main:Object(NameError)提供未定义的局部变量或方法,除非erb模板中使用的变量是全局变量 正确吗?在ruby 1.8.7(2010-01-10 patchlevel 249)[i486 linux]上 下面是有效的代码。如果我从变量名($db,$db\u root,$db\u root\u password)中删除Ruby erb为main:Object(NameError)提供未定义的局部变量或方法,ruby,erb,Ruby,Erb,erb为main:Object(NameError)提供未定义的局部变量或方法,除非erb模板中使用的变量是全局变量 正确吗?在ruby 1.8.7(2010-01-10 patchlevel 249)[i486 linux]上 下面是有效的代码。如果我从变量名($db,$db\u root,$db\u root\u password)中删除$,我会得到错误 $db = get_single_argument("database name") $db_root = get_single_argu
$
,我会得到错误
$db = get_single_argument("database name")
$db_root = get_single_argument("database root user name")
$db_root_passwd = get_single_argument("database root user password")
mysql_commands = get_conf_file("installer_mysql.erb")
puts mysql_commands.result #gives me the error
和获取配置文件过程
def get_conf_file(file)
return_array = Array.new
if (File.exists?(file))
return_array = ERB.new File.read(file)
end
return_array
end
您没有传递调用方的绑定,您应该:
puts mysql_commands.result(binding)
绑定包含当前范围内的所有变量引用。Ruby有一个称为a的概念,您可以将其视为一段代码可能具有的局部变量、self值、block等。您还可以将绑定视为代码的上下文 Erb的
result
方法采用可选的第二种方法,即绑定,用于评估您给出的代码,因此您可以执行以下操作
x = 1
ERB.new('x=<%= x %>').result(binding) #=> "x=1"
x=1
ERB.new('x=')。结果(绑定)#=>“x=1”
您是否有完整的堆栈跟踪和实际执行ERB模板的代码行?在模板上调用#result
之前,不应该发生任何事情,这要求传入调用方的绑定(其中包含所有变量引用)。忽略这一点,我看到了您的代码在做什么。请参阅我的答案以获得解释;)很好的解释。现在很好用。