Rails Root directory path?

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

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

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

    In Rails 3 and newer:

    Rails.root
    

    which returns a Pathname object. If you want a string you have to add .to_s. If you want another path in your Rails app, you can use join like this:

    Rails.root.join('app', 'assets', 'images', 'logo.png')
    

    In Rails 2 you can use the RAILS_ROOT constant, which is a string.

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

    In some cases you may want the Rails root without having to load Rails.

    For example, you get a quicker feedback cycle when TDD'ing models that do not depend on Rails by requiring spec_helper instead of rails_helper.

    # spec/spec_helper.rb
    
    require 'pathname'
    
    rails_root = Pathname.new('..').expand_path(File.dirname(__FILE__))
    
    [
      rails_root.join('app', 'models'),
      # Add your decorators, services, etc.
    ].each do |path|
      $LOAD_PATH.unshift path.to_s
    end
    

    Which allows you to easily load Plain Old Ruby Objects from their spec files.

    # spec/models/poro_spec.rb
    
    require 'spec_helper'
    
    require 'poro'
    
    RSpec.describe ...
    
    0 讨论(0)
  • 2020-11-30 17:34

    You can use:

    Rails.root
    

    But to to join the assets you can use:

    Rails.root.join(*%w( app assets))
    

    Hopefully this helps you.

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