Read more

Ruby: How to determine the absolute path relative to a file

Emanuel
September 18, 2020Software engineer at makandra GmbH

If you want to get the path of a file relative to another, you can use the expand_path method with either the constant __FILE__ or the method __dir__. Read this card for more information about __FILE__ and __dir__.

Example

Illustration UI/UX Design

UI/UX Design by makandra brand

We make sure that your target audience has the best possible experience with your digital product. You get:

  • Design tailored to your audience
  • Proven processes customized to your needs
  • An expert team of experienced designers
Read more Show archive.org snapshot

Structure:

.
├── bin
│   ├── format_changelog
├── CHANGELOG.md

bin/format_changelog:

#!/usr/bin/env ruby

changelog_path = ? # How to get the path to ../CHANGELOG.md independent of the working dir of the caller
changelog = File.read(changelog_path)

# ... further actions here

Ruby >= 2.0

changelog_path = File.expand_path('../CHANGELOG.md', __dir__)

Ruby < 2.0

changelog_path = File.expand_path('../../CHANGELOG.md', __FILE__)

Rails

changelog_path = Rails.root.join('CHANGELOG.md')
Posted by Emanuel to makandra dev (2020-09-18 08:39)