如何获取Rails应用程序的根目录路径?
在Rails 3及更新版本中:
Rails.root
它返回一个Pathname对象。如果你想要一个字符串,你必须添加。to_s。如果你想在你的Rails应用程序中使用另一个路径,你可以像这样使用join:
Rails.root.join('app', 'assets', 'images', 'logo.png')
在Rails 2中,你可以使用RAILS_ROOT常量,它是一个字符串。
您可以通过变量RAILS_ROOT访问rails应用程序路径。
例如:
render :file => "#{RAILS_ROOT}/public/layouts/mylayout.html.erb"
为了获得更高的正确性,你应该使用:
Rails.root.join('foo','bar')
这将允许您的应用程序在/不是目录分隔符的平台上工作,如果有人尝试在其中运行它。
除了所有其他正确答案,因为Rails。root是一个Pathname对象,这行不通:
Rails.root + '/app/assets/...'
您可以使用join之类的东西
Rails.root.join('app', 'assets')
如果你想要一个字符串,使用这个:
Rails.root.join('app', 'assets').to_s
在某些情况下,您可能需要Rails根目录,而不必加载Rails。
例如,当TDD的模型不依赖于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
它允许您轻松地从规范文件中加载普通旧Ruby对象。
# spec/models/poro_spec.rb
require 'spec_helper'
require 'poro'
RSpec.describe ...
module Rails
def self.root
File.expand_path("..", __dir__)
end
end
来源: https://github.com/rails/rails/blob/5259062868dcf10fbcf735d6520e6a14e15fdcdb/actionmailer/test/abstract_unit.rb#L12
推荐文章
- 如何确定一个数组是否包含另一个数组的所有元素
- Rails find_or_create_by多个属性?
- Rails ActiveRecord日期之间
- 是什么导致这个ActiveRecord::ReadOnlyRecord错误?
- Rails:dependent =>:destroy VS:dependent =>:delete_all
- 对于PostgreSQL表来说,多大才算太大?
- Rails:如何在Rails 4中引用CSS中的图像
- 如何使用RSpec的should_raise与任何类型的异常?
- Rails -嵌套包括活动记录?
- Delete_all vs destroy_all
- Rails获取“each”循环的索引
- 在rails redirect_to中传递参数
- Rails new vs create
- Rails has_many的别名
- Ruby:包含的反义词是什么?Ruby数组?