我有一个文件列表,我尝试获取相对路径
file = "/Users/yves/github/local/workshop/public/uploads/craftwork/image/1/a1d0.jpg"
Rails.public_path => "/Users/yves/github/local/workshop/public"
#我想得到=> “上传/工艺/图像/ 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?如果是的话,现在有什么好处?
答案 0 :(得分: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
答案 1 :(得分: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
答案 2 :(得分:0)
这就是我用过的:
"#{Rails.root}/public/spreadsheets/file_name.xlsx"