2013-01-24 42 views
0

我有一個文件列表,我試圖得到一個相對路徑如何在Rails 3.2中獲得相對路徑?

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

我想'relative_path_from'是在'Pathname'一個Ruby方法;並不知道Rails將其添加到字符串(並不意味着它沒有,但我沒有看到它在任何地方)。 AFAIK它期望另一個路徑名,而不是一個字符串,因爲它在它的參數上調用了'cleanpath'。 –

回答

2

你可以「欺騙」,只是使用子刪除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 
+0

好點..我太專注於文件路徑...現在得到它 – erwin

+2

現在你部署代碼並打破你的應用程序。 –

+1

@ Derk-Jan好點。我認爲他會使用Rails.root等來使其不可知目錄。 –

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 
0

這是我曾經用過:

"#{Rails.root}/public/spreadsheets/file_name.xlsx"