Rails Root directory path?

后端 未结 9 1174
攒了一身酷
攒了一身酷 2020-11-30 16:40

How do I get my Rails app\'s root directory path?

相关标签:
9条回答
  • 2020-11-30 17:17

    You can access rails app path using variable RAILS_ROOT.

    For example:

    render :file => "#{RAILS_ROOT}/public/layouts/mylayout.html.erb"
    
    0 讨论(0)
  • 2020-11-30 17:17
    module Rails
      def self.root
        File.expand_path("..", __dir__)
      end
    end
    

    source: https://github.com/rails/rails/blob/5259062868dcf10fbcf735d6520e6a14e15fdcdb/actionmailer/test/abstract_unit.rb#L12

    0 讨论(0)
  • 2020-11-30 17:22

    In addition to all the other correct answers, since Rails.root is a Pathname object, this won't work:

    Rails.root + '/app/assets/...'
    

    You could use something like join

    Rails.root.join('app', 'assets')
    

    If you want a string use this:

    Rails.root.join('app', 'assets').to_s
    
    0 讨论(0)
  • 2020-11-30 17:26

    For super correctness, you should use:

    Rails.root.join('foo','bar')
    

    which will allow your app to work on platforms where / is not the directory separator, should anyone try and run it on one.

    0 讨论(0)
  • 2020-11-30 17:26

    Simply by Rails.root or if you want append something we can use it like Rails.root.join('app', 'assets').to_s

    0 讨论(0)
  • 2020-11-30 17:26

    Simply By writing Rails.root and append anything by Rails.root.join(*%w( app assets)).to_s

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