2013-05-30 30 views
0

我對Ruby只有極少的知識,但我正在爲我的辦公室開發一個Vagrant VM。我將變量中的設置配置爲允許我們的每個開發人員輕鬆進行自定義,但是當我嘗試從外部文件包含變量時遇到了問題。奇怪的Ruby範圍界定問題(我認爲)

下面是我在做什麼(這工作)的基本要點是:

# Local (host) system info 
host_os = "Windows" 
nfs_enabled = false 

# IP and Port Configuration 
vm_ip_address = "33.33.33.10" 
vm_http_port = 80 
host_http_port = 8888 
vm_mysql_port = 3306 
host_mysql_port = 3306 # Warning, mysql port configuration using 3306 will interfere with any locally run MySQL server. 
local_sites_path = "D:\\Web" 
vm_sites_path = ENV["HOME"] + "/Sites" 

# VM Configuration 
vm_memory = "1024" 

Vagrant.configure("2") do |config| 
    ... do vagrant stuff here 

然而,這不起作用(config.local.rb的內容符合上述變量聲明):

if(File.file?("config.local.rb")) 
    require_relative 'config.local.rb' 
else 
    # Local (host) system info 
    host_os = "Mac" 
    nfs_enabled = true 

    # IP and Port Configuration 
    vm_ip_address = "33.33.33.10" 
    vm_http_port = 80 
    host_http_port = 8888 
    vm_mysql_port = 3306 
    host_mysql_port = 3306 # Warning, mysql port configuration using 3306 will interfere with any locally run MySQL server. 
    local_sites_path = ENV["HOME"] + "/Sites" 
    vm_sites_path = ENV["HOME"] + "/Sites" 

    # VM Configuration 
    vm_memory = "512" 
end 

Vagrant.configure("2") do |config| 
    ... do vagrant stuff here 

任何想法這裏發生了什麼?在這兩種情況下,變量聲明都在文件的頂部,所以我的理解是它們應該在全局範圍內。

這裏是config.local.rb的內容:

# Duplicate to config.local.rb to activate. Override the variables set in the Vagrantfile to tweak your local VM. 

# Local (host) system info 
host_os = "Windows" 
nfs_enabled = false 

# IP and Port Configuration 
vm_ip_address = "33.33.33.10" 
vm_http_port = 80 
host_http_port = 8888 
vm_mysql_port = 3306 
host_mysql_port = 3306 # Warning, mysql port configuration using 3306 will interfere with any locally run MySQL server. 
local_sites_path = "D:\\Web" 
vm_sites_path = ENV["HOME"] + "/Sites" 

# VM Configuration 
vm_memory = "1024" 

正如我所說的,我還沒有真正使用過的Ruby,但我知道編程和範圍都表示,這應該是工作的罰款。我已經檢查過(使用print語句)該腳本正在檢測幷包含該文件,但由於某種原因,除非在Vagrantfile中直接對配置設置進行硬編碼,否則它不起作用。

在此先感謝。

回答

1

以小寫字母開頭的變量是局部變量。它們被稱爲「本地」變量,因爲它們在它們定義的範圍內是局部的。就你而言,它們在config.local.rb的腳本本體中是本地的。除了config.local.rb的腳本主體外,其他任何地方都無法訪問它們。這就是他們「本地」的原因。

如果你想要一個全局變量,你需要使用一個全局變量。全局變量以$符號開頭。

+0

非常延遲的響應,但是這是問題。我沒有意識到ruby的全局變量需要'$'。 – ChimericDream

0

Jorg在他對局部變量和全局變量的解釋中是正確的。以下是可能的替代實現,可以做你想做的事情。

聲明你的配置config.local.rb作爲哈希:

{ 
    host_os: "Windows", 
    nfs_enabled: false 
    # etc, etc. 
} 

在你的其他的文件:

if File.exist?("config.local.rb")) 
    config = File.read("config.local.rb") 
else 
    config = { 
    host_os: "Mac", 
    nfs_enabled: true 
    # etc, etc. 
    } 
end 

config哈希目前擁有的所有數據。

如果這種方法看起來像它可以更好地滿足您的需求,那麼你或許應該把配置數據的YAML文件,而不是一個Ruby文件:How do I parse a YAML file?