Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby, removing parts a file path

Tags:

ruby

$local_path_to_css_file = File.expand_path(filename)

gives me

A/B/C/D/CSS/filename

or

A/B/C/D/CSS/layouts/filename

I want the result to be:

css/filename

or

css/layouts/filename

to remove everything up until css/.

like image 644
user1620024 Avatar asked Aug 23 '12 14:08

user1620024


1 Answers

You can use Pathname

require 'pathname'

absolute_path = Pathname.new(File.expand_path(filename))
project_root  = Pathname.new("/A/B/C/D") # you can set up root somewhere else, e.g. at point where script starts
relative      = absolute_path.relative_path_from(project_root)

relative.to_s # => "css/filename"
like image 142
Serge Balyuk Avatar answered Oct 13 '22 01:10

Serge Balyuk