How to use `Dir` to reference directories outside the working directory - ruby

The closest issue I could find on Stack Overflow was "Path outside of project, Ruby Dir", but the user appears to have been in the wrong development environment.
My issue is that the Dir class only gives information relative to the working directory. For instance, if I'm in C:/Users/john/Developer and this directory only has two subdirectories A and B then
$ ruby -e "p Dir['*']"
will return ["A", "B"]. This seems intended, but what if there is a directory C:/Users/jane/Developer/C that I need to run a command in using a script in C:/Users/john/Developer?
Running
Dir.chdir('C:/Users/jane/Developer/C') { %x[lerna clean] }
returns the error:
-e:1:in `chdir': No such file or directory # dir_s_chdir - C:/Users/jane/Developer/C (Errno::ENOENT)
from -e:1:in `<main>'
Is there a way to access directories outside of the working directory using the Dir class? It seems absurd to have to require scripts to be written at a root level.
Note, using %x[] to run the command in C:/Users/jane/Developer/C also doesn't seem to work.

Related

shell cd command in Ruby

Im trying to execute shell commands using ruby, but i cant change directory to PATH with blank spaces.
variable = %x[cd #{ENV["HOME"]}/Virtual\\ VMs/]
This is not working.
Thank you
To be absolutely safe:
path = File.join [ENV["HOME"], 'Virtual VMs']
variable = %x[cd '#{path}']
Please note, that cd has empty output, so to make sure it works one probably wants to do smth like:
path = File.join [ENV["HOME"], 'Virtual VMs']
variable = %x[cd '#{path}' && ls -la]
#⇒ "total 32\ndrwxr-xr-x ....."
What is ist supposed to do? You try to chdir into a directory, but then don't do anything in it. Your variable will be empty in any case. Aside from the fact that it is pointless to do, you can not reliably execute a cd by itself in this way, because it is not an executable file. You can see this if you just execute %x[cd]. You will get an Errno::ENOENT exception.
Maybe you should first describe in a broader context, what you want to achieve with your code. Where would you like to change the working directory? Within the Ruby process - in which case you have to use Dir.chdir - or in the child process - in which case you have to execute some command after the cd.

Failed to run a very simple ruby script [duplicate]

This question already has answers here:
Ruby: how to "require" a file from the current working dir?
(5 answers)
Closed 6 years ago.
I have create a Ruby class Worker, file name is Worker.rb:
class Worker
def initialize
...
end
def doTask(task_name)
...
end
end
Then, I created another Ruby script file, named run.rb (it requires Worker):
require 'Worker'
worker = Worker.new
worker.doTask("sort")
Both two ruby files are located directly under the project folder:
ProjectFolder/
-- Worker.rb
-- run.rb
I run the run.rb under project folder by command:
ruby run.rb
But get following error:
/Users/John/.rvm/rubies/ruby-2.3.0/lib/ruby/2.3.0/rubygems/core_ext/kernel_require.rb:55:in `require': cannot load such file -- Worker (LoadError)
from /Users/John/.rvm/rubies/ruby-2.3.0/lib/ruby/2.3.0/rubygems/core_ext/kernel_require.rb:55:in `require'
from runme.rb:1:in `<main>'
Why?
I figured out after checking #Geo 's github project, I should use:
require_relative "worker"
require looks for the required file from the so called load path and not the current directory. Since the syntax for looking in the current directory was awkward Ruby 1.9 introduces require_relative, which looks in the current directory.
Change your code like this:
require_relative "Worker"
instead of
require "Worker"
The reason this does not work is because the current directory is not part of ruby's default load path.
If you run the following command, you will see what the current load path is and it will confirm that the current directory is not part of that path.
ruby -e 'puts $LOAD_PATH'
This should answer your primary question as to why the required file was not loaded.
As for a solution, require_relative will work and is probably the best solution in this case.
There are however still cases were inserting directories into the load path is helpful, if not required. For example say you have a script that can be run anywhere in the file system and you want the flexibility to require a particular version of your co-worker's foo class.
/afs/some_cell/u/john/some_ruby_lib
prod/
foo.rb
bar.rb
prev/
foo.rb
bar.rb
beta/
foo.rb
bar.rb
In a case like this either setting the RUBYSIM var (maybe in a wrapper) or setting the proper include path on the ruby command line can be a useful solution.
Again, your co-worker has not published this as a gem, he is just providing a shared directory.
There are several ways you can insert directories into the load path when it is appropriate, as demonstrated below:
You can use the -I command line flag
ruby -I some_path -e 'puts $LOAD_PATH'
You can set the RUBYLIB env var to include your current directory.
on unix/linix/osx
export RUBYLIB=some_path
on windows
set RUBYLIB=some_path

ruby require command not loading correctly

First post, "Hello World"
I am working through the lynda videos on Ruby and am just getting to the part of requiring content from .rb files in irb. An example patch we made is named contact_info.rb and from irb I am trying to require that file. When executed it comes back with the attached below.
Some light googling made it seem like this is maybe a yosemite issue (running 10.10.3.), but I'm not sure how to troubleshoot.
Thanks all
irb(main):006:0> require contact_info.rb
LoadError: cannot load such file -- contact_info.rb
from /System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/lib/ruby/2.0.0/rubygems/core_ext/kernel_require.rb:55:in 'require'
from /System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/lib/ruby/2.0.0/rubygems/core_ext/kernel_require.rb:55:in 'require'
from (irb):6
from /usr/bin/irb:12:in '<main>'
you can use require_relative 'contact_info'.
Assuming the file is in your current directory, type this in your command line:
irb -r './contact_info.rb'
First, note that with any require statement, you omit the file extension:
require 'contact_info'
When you require a file, ruby only looks in certain directories on your computer for the file. You can see which directories those are by running the following code:
p $LOAD_PATH
In ruby 1.8.7, the $LOAD_PATH array included ".", or the current directory, which means your code would have worked. But, including the current directory in $LOAD_PATH was deemed a security risk, so now you have to do something different:
1) One option is to use a relative path for the file you specify in the require statement:
require './contact_info'
The path is relative to the current directory. That works fine if you have this structure:
/some/dir/
your_prog.rb
contact_info.rb
And you switch directories to /some/dir and then run your_prog.rb:
~$ cd /some/dir
/some/dir$ ruby my_prog.rb
The require statement works--no problems. However, what if you do this:
/some/dir$ cd ..
/some$ ruby ./dir/your_prog.rb
Now, the current directory is /some, and require './contact_info' tells ruby to look in the /some directory for contact_info.rb--but it isn't there, so you will get the error:
`require': cannot load such file -- ./contact_info.rb (LoadError)
2) To cure that problem, ruby added require_relative. Paths specified with require_relative are relative to the location of the file that contains the require_relative statement. As a result, the statement:
#your_prog.rb:
require_relative './contact_info'
...will look in the directory containing your_prog.rb for the file contact_info.rb. Now, doing this:
/some$ ruby ./dir/your_prog.rb
will work fine. And in fact, in the require_relative you don't even have to write the ./ in the path:
#your_prog.rb:
require_relative 'contact_info' #Look for contact_info.rb in the same
#directory that contains this file
require_relative '../contact_info' #Look for contact_info.rb one directory
#above the directory that contains this file
I am working through the lynda videos on Ruby and am just getting to
the part of requiring content from .rb files in irb.
In my opinion, it's not a good idea to use irb for much of anything. A better option is to create a couple of files called 1.rb, 2.rb, 3.rb, and do your coding in those files.

Ruby 1.9.3 - Locate file local to ruby program regardless of where program is called from

I've been working on my first Ruby project, and in the process of trying to organize my files into different directories, I've run into trouble with having .rb files load non-ruby files (e.g. .txt files) local to themselves.
For example, suppose a project has the following structure:
myproject/
bin/
runner.rb
lib/
foo.rb
fooinfo.txt
test/
testfoo.rb
And the file contents are as follows:
runner.rb
require_relative '../lib/foo.rb'
foo.rb
File.open('./fooinfo.txt') do |file|
while line = file.gets
puts line
end
end
If I cd to lib and run foo.rb, it has no trouble finding fooinfo.txt in its own directory and printing its contents.
However, if I cd to bin and run runner.rb, I get
in `initialize': No such file or directory - ./fooinfo.txt (Errno::ENOENT)
I assume this is because File.open searches relative to whatever directory the top level program is run from.
Is there a way to ensure that foo.rb can find fooinfo.rb regardless of where it is run/required from (assuming that foo.rb and fooinfo.rb always maintain the same location relative to eachother)?
I'd like to be able to run foo.rb from bin/runner.rb, and a test file in test/, and have it be able to find fooinfo.txt in both cases.
Ideally, I'd like to have a solution that would work even if the entire myproject directory were moved.
Is there something like require_relative that can locate a non-ruby file?
Try using __FILE__ and File.dirname to build absolute paths. For example:
File.open(File.expand_path(File.dirname(__FILE__)) + './fooinfo.txt') do |file|
...
end
In this case, the simplest thing is to just change
File.open('./fooinfo.txt')
to
File.open('../lib/fooinfo.txt')
That will work from from any project subdirectory directly under your project root (including lib/).
The more robust solution, useful in larger projects, is to have a PROJECT_ROOT constant that you can use from anywhere. If you have lib/const.rb:
module Const
PROJECT_ROOT = File.expand_path("..", File.dirname(__FILE__))
end
Then (assuming you've requireed that file) you can use:
File.open(Const::PROJECT_ROOT + '/lib/fooinfo.txt')

Rails irb default directory

I'm trying to include a source code file when I run irb but irb is unable to find it.
For example, say I am in the following directory in terminal:
/dan/rubyapp/
Assume I have a file named "firstapp.rb" in /dan/rubyapp/
I startup irb and from the irb prompt I type
> require "firstapp.rb"
but the file can't be found. If I type "Dir.pwd" it shows as
/dan/rubyapp/
The only way I can get "require" to work is if I include the full path like so
> require "/dan/rubyapp/firstapp.rb"
Is that the only way I can get this to work? All the tutorials I see online simply do "require file_name" so I assumed it would work.
here is the output from $: at irb
ruby-1.9.2-p0 > $:
=> ["/Users/Daniel/.rvm/gems/ruby-1.9.2-p0/gems/wirble-0.1.3/bin",
"/Users/Daniel/.rvm/gems/ruby-1.9.2-p0/gems/wirble-0.1.3/lib",
"/Users/Daniel/.rvm/rubies/ruby-1.9.2-p0/lib/ruby/site_ruby/1.9.1",
"/Users/Daniel/.rvm/rubies/ruby-1.9.2-p0/lib/ruby/site_ruby/1.9.1/x86_64-darwin10.4.0",
"/Users/Daniel/.rvm/rubies/ruby-1.9.2-p0/lib/ruby/site_ruby",
"/Users/Daniel/.rvm/rubies/ruby-1.9.2-p0/lib/ruby/vendor_ruby/1.9.1",
"/Users/Daniel/.rvm/rubies/ruby-1.9.2-p0/lib/ruby/vendor_ruby/1.9.1/x86_64-darwin10.4.0",
"/Users/Daniel/.rvm/rubies/ruby-1.9.2-p0/lib/ruby/vendor_ruby",
"/Users/Daniel/.rvm/rubies/ruby-1.9.2-p0/lib/ruby/1.9.1",
"/Users/Daniel/.rvm/rubies/ruby-
1.9.2-p0/lib/ruby/1.9.1/x86_64-darwin10.4.0"]
The problem is that the current working directory is no longer in your path (as of Ruby 1.9.2). There are a few different ways around the problem.
1) In a ruby file itself, you can use the method require_relative instead of require. This will load a file relative to the loaction of the file containing the require_relative method:
http://extensions.rubyforge.org/rdoc/classes/Kernel.html
require_relative 'firstapp.rb'
This, however, will not work in irb.
2) Your other option is to include the current path in your argument to the require method. This will work in irb or in a ruby file. For instance:
require './firstapp.rb'
The reason this was implemented in ruby was to avoid inadvertently requiring the wrong file if there are different files with the same name in different directories in the path (similar to how *nix does not include the current directory "." in its path)
A couple of things to try:
1) Drop the .rb from the end of your require so you have:
require 'firstapp'
You don't normally add the .rb to a require (only to a load) - have a look here for more details:
http://www.fromjavatoruby.com/2008/10/require-vs-load.html
2) Failing that, make sure the current directory is on your load path - in irb execute:
p $:
and it will print out your ruby load path - check for an entry for "." (mine is the last entry)

Resources