How to open a file at the same folder of the ruby script?
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__)))
精彩评论