File Methods: Part Two
In last week's tip, we learned about __FILE__ , which gives us the path to the current file, and File.expand_path which gives us the full absolute filepath. File.dirname As the name implies, File.dirname will give us the path to the directory of a file. Combining this with what we learned last week, this means that if we had a file at ruby_weekly/sample.rb with the following contents: puts File.dirname(__FILE__)
..we could run it and see the directory: $ ruby ruby_weekly/sample.rb
ruby_weekly
Interestingly, in Ruby 3.1, File.dirname introduced an optional second parameter, an integer which represents how many levels to go up the directory tree. So for instance, if the full path to the above file is /Users/jemmaissroff/ruby_weekly/sample.rb , and we edit the file slightly to use the full path, and a second argument: puts File.dirname(
File.expand_path(__FILE__), 2
)
we'll see the path to the directory two up the directory tree from our file: $ ruby ruby_weekly/sample.rb
/Users/jemmaissroff/
File.join Last up in File methods (I promise we're getting there!), File.join joins its arguments with a "/" to create a filepath. For instance: File.join("app", "controllers", "file_name.rb")
# => "app/controllers/file_name.rb"
Notice this is exactly the same as if we'd run: ["app", "controllers", "file_name.rb"].join("/")
# => "app/controllers/file_name.rb"
This can be useful to construct a file path from a relative file. Before Ruby 3.1 introduced the second argument to File.dirname , it was often used to join ".." which takes us one directory up the tree. Why are all of these file methods relevant? Some gems or Ruby applications often use a combination of them to load the appropriate files. Take a look at this code (split across multiple lines for email formatting reasons) and see if you now can decipher exactly what it's doing! File.expand_path(
File.join(
File.dirname(__FILE__, 2), 'lib'
)
)
|