Relative path to your project directory

前端 未结 2 1216
陌清茗
陌清茗 2020-12-23 17:07

In my Ruby project I am using a mess of things like moving and editing files on several remote boxes and I really need something like a relative path to my root project dire

相关标签:
2条回答
  • 2020-12-23 17:40

    You can get current directory (directory of current file) with this

    File.dirname(__FILE__)
    

    You can then join it with relative path to the root

    File.join(File.dirname(__FILE__), '../../') # add proper number of ..
    

    Or you can use expand_path to convert relative path to absolute.

    ENV['BUNDLE_GEMFILE'] = File.expand_path('../../Gemfile', File.dirname(__FILE__))
    

    Or you can calculate relative path between two dirs.

    require 'pathname'; 
    puts Pathname.new('/').relative_path_from(Pathname.new('/some/child/dir/')).to_s
    # => ../../..
    
    0 讨论(0)
  • 2020-12-23 17:58
    __dir__
    

    Since Ruby 2, you can simply use Kernel-function :__dir__ to get the absolute directory-path of the current file. So, to give an example, you could set a constant ROOT_DIR at the start of your project in the (config.rb, environments.rb, constants.rb, or whatever you call it).

    See Ruby Documentation

    0 讨论(0)
提交回复
热议问题