How to open a file in the same ruby ​​script folder?

The following .rbscript works fine if you excuse me in the script folder:

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

File.openwill fail if the script runs outside the script folder. How can I provide a script path to db.yml? Thank!

+3
source share
2 answers

This should work:

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

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

+9
source

If you find that you want to make this a bunch, you might consider adding a script directory to your boot path (especially in version 1.9.2, where "." Is no longer in the boot path):

$: << File.expand_path(File.join(File.dirname(__FILE__)))
+1
source

Source: https://habr.com/ru/post/1761280/


All Articles