0

我有一个文件列表,我尝试获取一个相对路径

file = "/Users/yves/github/local/workshop/public/uploads/craftwork/image/1/a1d0.jpg"
Rails.public_path => "/Users/yves/github/local/workshop/public"

# 我正在尝试获取 => "uploads/craftwork/image/1/a1d0.jpg"

file.relative_path_from(Rails.public_path) # is wrong 
# raising :  undefined method `relative_path_from' for #<String  ( file is a String..)

# so I tried to use Pathname class
Pathname.new(file).relative_path_from(Rails.public_path)

# but the I get another error
# undefined method `cleanpath' for String

在 Rails 3.2 中是否不推荐使用 relative_path_from ?如果是的话,现在有什么好的?

4

3 回答 3

2

由于这些属性现在返回字符串,我们可以将它们转换回路径名:

public_path = Pathname.new( Rails.public_path )
file_path = Pathname.new( file )

然后使用相对路径函数,最后将其转换回字符串

relative_path = file_path.relative_path_from( public_path ).to_s 

一起变成

Pathname.new( file ).relative_path_from( Pathname.new( Rails.public_path ) ).to_s 
于 2013-06-05T20:30:55.933 回答
1

您可以“作弊”并使用 sub 删除 public_path ...

$ cat foo.rb 
file = "/Users/yves/github/local/workshop/public/uploads/craftwork/image/1/a1d0.jpg"
public_path = "/Users/yves/github/local/workshop/public"
puts file.sub(/^#{public_path}\//, '')

$ ruby foo.rb 
uploads/craftwork/image/1/a1d0.jpg
于 2013-01-24T18:10:00.000 回答
0

这是我用过的:

"#{Rails.root}/public/spreadsheets/file_name.xlsx"
于 2016-09-16T12:32:08.137 回答