本文翻译自:Rails Root directory path?
如何获取Rails应用程序的根目录路径?
#1楼
参考:https://stackoom.com/question/FcuN/Rails根目录路径
#2楼
In addition to all the other correct answers, since Rails.root
is a Pathname
object, this won't work: 除了所有其他正确的答案,由于Rails.root
是一个Pathname
对象,这将不起作用:
Rails.root + '/app/assets/...'
You could use something like join
你可以使用像join
这样的东西
Rails.root.join('app', 'assets')
If you want a string use this: 如果你想要一个字符串使用这个:
Rails.root.join('app', 'assets').to_s
#3楼
You can use: 您可以使用:
Rails.root
But to to join the assets you can use: 但要加入您可以使用的资产:
Rails.root.join(*%w( app assets))
Hopefully this helps you. 希望这会对你有所帮助。
#4楼
In some cases you may want the Rails root without having to load Rails. 在某些情况下,您可能需要Rails根,而无需加载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
. 例如,您TDD'ing不通过要求取决于on Rails的模型时获得更快的反馈周期spec_helper
代替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文件中加载Plain Old Ruby Objects。
# spec/models/poro_spec.rb
require 'spec_helper'
require 'poro'
RSpec.describe ...
#5楼
In Rails 3 and newer: 在Rails 3和更新版本中:
Rails.root
which returns a Pathname
object. 它返回一个Pathname
对象。 If you want a string you have to add .to_s
. 如果你想要一个字符串,你必须添加.to_s
。 If you want another path in your Rails app, you can use join
like this: 如果您想在Rails应用程序中使用其他路径,可以使用如下join
:
Rails.root.join('app', 'assets', 'images', 'logo.png')
In Rails 2 you can use the RAILS_ROOT
constant, which is a string. 在Rails 2中,您可以使用RAILS_ROOT
常量,这是一个字符串。
#6楼
You can access rails app path using variable RAILS_ROOT
. 您可以使用变量RAILS_ROOT
访问rails app路径。
For example: 例如:
render :file => "#{RAILS_ROOT}/public/layouts/mylayout.html.erb"