Method: Path#relocate
- Defined in:
- lib/path.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>
145 146 147 148 149 150 151 |
# File 'lib/path.rb', line 145 def relocate(from, to, new_ext = ext, &updater) updater ||= lambda { |path| path } renamer = lambda { |rel| Path.new(updater.call(rel.rm_ext)).add_ext(new_ext) } Path.new(to) / renamer.call(self % from) end |