ohho
ohho

Reputation: 51921

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 the script folder. How can I supply the script's path to db.yml? Thanks!

Upvotes: 3

Views: 2603

Answers (2)

todb
todb

Reputation: 329

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__)))

Upvotes: 1

Christoph Lupprich
Christoph Lupprich

Reputation: 1190

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.

Upvotes: 9

Related Questions