2011-12-29 59 views
0

erb給我undefined local variable or method for main:Object (NameError),除非在erb模板中使用的變量是一個全局變量。erb給我 - 未定義的局部變量或方法爲主:對象(NameError)

這是正確的嗎?關於紅寶石1.8.7(2010-01-10 patchlevel 249)[i486-linux]

下面是可用的代碼。如果我從變量名稱($ db,$ db_root,$ db_root_password)中刪除$,我得到錯誤。

$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 

get_conf_file程序

def get_conf_file(file) 

return_array = Array.new 
if (File.exists?(file)) 
    return_array = ERB.new File.read(file) 
end 
return_array 
end 
+0

你有完整的堆棧跟蹤和代碼行你在哪裏實際執行ERB模板?除非在模板上調用#result,否則不會發生任何事情,這需要傳入調用方的綁定(其中包含所有變量引用)。 – d11wtq 2011-12-29 09:57:07

+0

忽略這一點,我看到你的代碼在做什麼。看到我的答案的解釋;) – d11wtq 2011-12-29 09:59:22

回答

7

Ruby有一個概念叫做binding,你可能認爲這個概念是一段代碼可能具有的局部變量,自身值,塊值等。您也可以將綁定視爲代碼的上下文。

厄爾布的result方法接受一個可選的第二個方法,是與結合來評價你給它的代碼,所以你可以做的東西一樣

x = 1 
ERB.new('x=<%= x %>').result(binding) #=> "x=1" 
+0

很好的解釋。現在很好地工作。 – Radek 2011-12-29 10:22:26

1

你沒有傳遞調用者的結合,你應該:

puts mysql_commands.result(binding) 

的結合包含了所有的變量引用在當前的範圍內。

相關問題