开发者

How to open a file at the same folder of the ruby script?

开发者 https://www.devze.com 2023-01-12 16:24 出处:网络
The following .rb script runs fine if excuting at the script\'s folder: db = YAML::load(File.open(\'db.yml\'))

The following .rb script runs fine if excuting at the script's folder:

  db = YAML::load(File.open('db.yml'))
  ActiveRecord::Base.establish_connection(db)

The File.open will fail if the script is running outside th开发者_Python百科e script folder. How can I supply the script's path to db.yml? Thanks!


This should work:

db_file = File.join(File.dirname(__FILE__), "db.yml")

Edit: I got a little bit confused with the script folder, this should work now.


If you find yourself wanting to do this a bunch, you might consider adding the script's directory to your load path (especially in 1.9.2 where "." is no longer in the load path):

$: << File.expand_path(File.join(File.dirname(__FILE__)))
0

精彩评论

暂无评论...
验证码 换一张
取 消