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 book lover

Growing Rails Applications in Practice

Check out our e-book. Learn to structure large Ruby on Rails codebases with the tools you already know and love.

  • Introduce design conventions for controllers and user-facing models
  • Create a system for growth
  • Build applications to last
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)