Method: Path#relocate

Defined in:
lib/epath.rb

#relocate(from, to, new_ext = ext, &updater) ⇒ Object

Relocates this path somewhere else.

Without a block, this method is a simple shorcut for a longer expression that proves difficult to remember in practice:

to / (self.sub_ext(new_ext) % from)

That is, it relocates the original path to a target folder to appended with the relative path from a source folder from. An optional new extension can also be specified, as it is a common use case.

With a block, the relative path is passed to the block for user update, without the last extension. new_ext is added after (or the original extension if not provided).

from = Path('pictures')
to   = Path('output/public/thumbnails')
earth = from / 'nature/earth.jpg'

earth.relocate(from, to)
# => #<Path output/public/thumbnails/nature/earth.jpg>

earth.relocate(from, to, '.png') { |rel|
  "#{rel}-200"
}
# => #<Path output/public/thumbnails/nature/earth-200.png>


134
135
136
137
138
139
140
# File 'lib/epath.rb', line 134

def relocate(from, to, new_ext = ext, &updater)
  updater ||= lambda { |path| path }
  renamer = lambda { |rel|
    Path(updater.call(rel.rm_ext)).add_ext(new_ext)
  }
  to / renamer.call(self % from)
end