如何在Ruby中包含文件中的代码?

如何在Ruby中包含文件中的代码?,ruby,include,Ruby,Include,我是Ruby新手,正在研究如何在脚本中包含文件。我尝试了require和include,但没有成功 这是我想要包含的文件,值得注意的是它不是一个模块 # file1.rb if Constants.elementExist(driver, 'Allow') == true allowElement = driver.find_element(:id, 'Allow') allowElement.click() sleep 1 wait.until { driver.fin

我是Ruby新手,正在研究如何在脚本中包含文件。我尝试了
require
include
,但没有成功

这是我想要包含的文件,值得注意的是它不是一个模块

# 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
# file2.rb
module File2
  module IOS
    # include file1.rb
  end
end
该文件包含几行代码,在我的例子中,这些代码是可重用的或可重复的。它不在类或模块内。这是一个简单的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
# file2.rb
module File2
  module IOS
    # include file1.rb
  end
end
这样,它应该只在
file2.rb
内部运行
file1.rb
的代码

如何在Ruby中做到这一点?

根据,
要求
具有以下行为:

如果文件名未解析为绝对路径,则将 在
$LOAD\u PATH($:)
中列出的目录中搜索

这意味着要在
file2.rb
中运行
file1.rb
的代码,其中两个文件位于完全相同的文件夹中,您必须执行以下操作:

# file2.rb
module File2
  module IOS
    # Absolute path to file1.rb, adding '.rb' is optional
    require './file1'
  end
end
使用:


require\u relative'file1.rb'

我建议您为您试图用代码实现的目标提供更多的上下文,因为您可能会在
file2.rb
上遇到范围问题,在
file1.rb
中有未定义的对象/类,例如
driver
password
常量
。即使您设法做到了这一点在你的名称空间中“包含”这个文件你预计会发生什么?在这一点上,除了@Oxfist的评论,你最好从命令行使用
ruby file1.rb
,或者在脚本中使用
load
。我以前尝试过需要“file1”,但它不起作用。顺便说一句,它们在同一路径/目录中@ジョンピーター 更新问题并发布您遇到的错误,以便我可以帮助您“但它不起作用”“。包括错误消息。有一百万种不同的方式可能不起作用,但您仍然没有说它是哪一种。这里的问题是OP的目录不太可能位于
$LOAD\u PATH
中。为了帮助实现这一点,ruby提供了一种类似的方法来要求文件相对于调用文件
require\u relative
,我认为这更符合您的意图