如何获取Rails应用程序的根目录路径?


当前回答

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.root 并附加任何 Rails.root。Join (*%w(应用程序资产)).to_s

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.root

但要加入您可以使用的资产:

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

希望这能帮到你。

为了获得更高的正确性,你应该使用:

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

这将允许您的应用程序在/不是目录分隔符的平台上工作,如果有人尝试在其中运行它。

您可以通过变量RAILS_ROOT访问rails应用程序路径。

例如:

render :file => "#{RAILS_ROOT}/public/layouts/mylayout.html.erb"