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 online protection

Rails Long Term Support

Rails LTS provides security patches for old versions of Ruby on Rails (2.3, 3.2, 4.2 and 5.2)

  • Prevents you from data breaches and liability risks
  • Upgrade at your own pace
  • Works with modern Rubies
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)