Rails根目录路径?

本文翻译自: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"
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值