如何在Ruby中包含文件中的代码?
问题描述:
我是Ruby新手,想弄清楚如何在脚本中包含文件。我试过require
和include
但它不起作用。如何在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中做到这一点?
答
按照Ruby docs,require
有以下行为:
如果文件名不能解析为一个绝对路径,这将是 搜索在
$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
我建议你到你想实现的代码是什么提供更多的情况下,因为你可能已经在'file2.rb'范围的问题与'file1.rb'中的未定义对象/类,例如'driver','password'或'Constants'。 – Oxfist
即使你设法将这个文件“包含”在你的命名空间中,你预期会发生什么?在这一点上,除了@Oxfist提出的意见之外,你还可以使用命令行中的'ruby file1.rb'或脚本中的'load'。 – engineersmnky