user762579
user762579

Reputation:

how to get a relative path in Rails 3.2?

I have a list of files , and I try to get a relative path

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

# I am trying to get => "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

Is relative_path_from deprecated in Rails 3.2 ? if yes , what's the good one now?

Upvotes: 1

Views: 2842

Answers (3)

Atchyut Nagabhairava
Atchyut Nagabhairava

Reputation: 1413

This is what I have used:

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

Upvotes: -1

Derk-Jan
Derk-Jan

Reputation: 1954

Since these properties now return strings, we can convert them back into path names:

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

and then use the relative path function, finally converting it back into a string

relative_path = file_path.relative_path_from( public_path ).to_s 

That together becomes

Pathname.new( file ).relative_path_from( Pathname.new( Rails.public_path ) ).to_s 

Upvotes: 3

Philip Hallstrom
Philip Hallstrom

Reputation: 19879

You could 'cheat' and just remove the public_path using sub...

$ 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

Upvotes: 1

Related Questions