2017-10-04 51 views
-5

我是Ruby新手,想弄清楚如何在腳本中包含文件。我試過requireinclude但它不起作用。如何在Ruby中包含文件中的代碼?

這是我想包括的文件,值得注意的是它不是一個模塊。

# file1.rb 
if Constants.elementExist(driver, 'Allow') == true 
    allowElement = driver.find_element(:id, 'Allow') 
    allowElement.click() 
    sleep 1 
    wait.until { 
    driver.find_element(:id, 'Ok').click() 
    } 
    username = driver.find_element(:id, 'UsernameInput') 
    username.clear 
    username.send_keys Constants.itech_email 
    password = driver.find_element(:id, 'PasswordInput') 
    password.clear 
    password.send_keys Constants.itechPass 
    driver.find_element(:id, 'Login').click 
else 
    username = driver.find_element(:id, 'UsernameInput') 
    username.clear 
    username.send_keys Constants.itech_email 
    password = driver.find_element(:id, 'PasswordInput') 
    password.clear 
    password.send_keys Constants.itechPass 
    driver.find_element(:id, 'Login').click 
end 

該文件包含幾行代碼,在我的情況下可重複使用或重複使用。它不在課堂或模塊中。這是一個簡單直觀的Ruby腳本,我想在模塊中的第二個腳本中使用它。

# file2.rb 
module File2 
    module IOS 
    # include file1.rb 
    end 
end 

這樣,它應該只是運行的file1.rb裏面的代碼file2.rb

我該如何在Ruby中做到這一點?

+1

我建議你到你想實現的代碼是什麼提供更多的情況下,因爲你可能已經在'file2.rb'範圍的問題與'file1.rb'中的未定義對象/類,例如'driver','password'或'Constants'。 – Oxfist

+0

即使你設法將這個文件「包含」在你的命名空間中,你預期會發生什麼?在這一點上,除了@Oxfist提出的意見之外,你還可以使用命令行中的'ruby file1.rb'或腳本中的'load'。 – engineersmnky

回答

0

按照Ruby docsrequire有以下行爲:

如果文件名不能解析爲一個絕對路徑,這將是 搜索在$LOAD_PATH ($:)列出的目錄。

這意味着爲了運行裏面file2.rb,其中兩個文件都在完全相同的文件夾file1.rb的代碼,你必須做到以下幾點:

# file2.rb 
module File2 
    module IOS 
    # Absolute path to file1.rb, adding '.rb' is optional 
    require './file1' 
    end 
end 
+0

我試過之前 要求'file1' 但它沒有工作。他們在相同的路徑/目錄順便說一句。 –

+0

@ジョンピーター更新問題,併發布錯誤,所以我可以幫你 – Oxfist

+1

「butt it does not work」。包含**錯誤消息**。有一百萬種不同的方式,它可能無法正常工作,你仍然沒有說它是哪一個 – Max

相關問題