ruby / pathname

Pathname represents the name of a file or directory on the filesystem, but not the file itself.
Other
26 stars 16 forks source link

Request to add Dir#chdir to Pathname functionality. #25

Open rempargo opened 1 year ago

rempargo commented 1 year ago

Since most use-full functionalities from Dir are included in Pathname, I'm surprised that Dir.chdir is not included. As the whole Pathname class is as pleasant facade for File, FileTest, Dir and FileUtils, and working with it should be 'unsurprising', I think the chdir command should also be a part of the Pathname class/

hsbt commented 3 weeks ago

@rempargo Can you explain detailed usecase of Pathname#chdir? Inconsistency reason is weak to add Pathname#chdir again since Ruby 1.9.

knu commented 3 weeks ago

One thing I don't feel quite right is that calling the chdir method on a relative Pathname would make the receiver no longer meaningful.

zverok commented 3 weeks ago

@hsbt My thinking in this case (that led to the PR) is that:

  1. In general, I feel that consistency is not that weak reason. For me, Pathname is an OO wrapper around the “filesystem object,” which allows to do all (or a huge part) of what File/Dir/FileUtils module functions allow to do without leaving the comfort of OO wrapper. Like, you switch to Pathname for pathing around references to filesystem objects, and then everything you might want to do with filesystem (read/write/rename/get and set properties) can be done with path.some_method. So, just some methods not existing in Pathname might lead to user confusion (and even avoiding the OO wrapper because “I don’t remember when it might turn out it doesn’t have the method I expected to be there”). Especially after instance method was introduced to Dir, it became more confusing (as “simpler” Dir object now can do things “more advanced” Pathname object can’t).
  2. Say, Rails.root is a Pathname, and it is usually advised (and even checked by some linters) that people wouldn’t do File.read("{Rails.root}/my/config.yml"), but do instead Rails.root.join('my', 'config.yml').read. Conversely, say, some application maintanance tasks might want to do chdir to some subdirectory of the app (to run some scripts there), and therefore Rails.root.join('maint', 'scripts').chdir { exec('something') } is not unimaginable, at least!
  3. I understand the concern about the relative Pathname becoming “irrelevant” after chdir to it (unlike Dir#chdir, as Dir object is bound to FS object early), but I don’t think it is too confusing, considering the nature of the Pathname. It is more or less the same as that after path.delete you can’t anymore do path.read: you performed some operation, value stayed the same, referred object changed, at least it is easy to explain.