I'm using ruby v1.9.1 in combination with vim and I execute my scripts with:
:!ruby "%"
my scripts are running fine if I add:
$:.unshift File.dirname(__FILE__)
to add the path of this file to the LOAD_PATH of ruby. If I omit this line my require statements to local scripts aren't working anymore.
Is there a way to pass the path of the file to rubys LOAD_PATH? Something like (completly fictional):
:!ruby "%" --add-to-load-path
I did some research before and stubled upon require_relative, but this has the same effect as require and is not working.
You can use the -I option of the ruby executable and write something like the following:
:!ruby -I%:p:h. %
See ruby --help for further information and file modifiers.
Edited: see comments.
Related
I would like to write a CLI application wrapped into a Gem that can be invoked the same way git commands are invoked, or gem commands. Eg when running say "git clone " you don't need to precede it with 'ruby'. However, the tutorials and articles I've seen so far about writing gems, don't show this. The examples either require you to run your gem through irb, with appropriate requires, or you run it like 'ruby '. This is not what I want. If you know of any tutorials that cover this, then that would be great.
Thanks.
The "#!" line at the start of a script tells your shell which executable to execute the script with. In this case, it tells it to find the Ruby executable from the environment and give the script to it for execution.
By means of example, I have a file called "hi", with the following:
#!/usr/bin/env ruby
puts "hi!"
I make it executable:
$ chmod a+x hi
Then I can execute it directly, without explicitly invoking the Ruby interpreter:
$ ./hi
hi!
Per the tutuorial you would simply provide such a file which requires your gem and whatnot, and provide it in the executables property of your gemspec:
Gem::Specification.new do |s|
# ...
s.executables << 'hi'
When the gem is installed, the hi script would be installed into a location discoverable on the path, so you could then invoke it.
I am trying to make a command line tool. I already have a ruby script (one file). But I want to project it as a normal command line command.
Right now I have to go into the directory where the script is and type ruby script.rb for it to function but i want to make a command such as script [option] from directory and it should process the required option in the script.
Do I need to make an independent ruby gem for this? I have read about some gems like thor and commander but I am not able to use them properly.
How can I make this command line tool?
PS: An example can be the twitter gem and a command line tool 't' which is also a gem.
Ruby, because it's a general-programming language, makes it easy to create command-line scripts. Here's a basic script you can build upon:
#!/usr/bin/env ruby
require 'optparse'
args = {}
OptionParser.new do |opt|
opt.on('-i', '--input FILE', 'File to read') { |o| args[:file_in] = o }
opt.on('-o', '--output FILE', 'File to write') { |o| args[:file_out] = o }
end.parse!
abort "Missing input or output file" unless (args[:file_in] && args[:file_out])
File.write(args[:file_out], File.read(args[:file_in]))
Here's what's happening:
#!/usr/bin/env ruby is commonly called a "bang line". The shell will look for this line at the top of a file to determine what application can read the file and execute/interpret it. env is an application that will look through the user's PATH environment variable and return the first Ruby found as the Ruby to execute the script. Using this makes the script work with Rubies in the normal /usr/bin, /usr/local/bin or when managed by rbenv or RVM.
require 'opt parse' pulls in Ruby's command-line parser class OptionParser, which makes it easy to set up traditional flags, such as -i path/to/file/to/read, -o path/to/file/to/write, or long parameters, like --input or --output. It also automatically supplies the -h and --help flags to return formatted help text for the script. OptionParser is a bit of a learning-curve, so play with the complete example and you'll figure it out.
The rest should be pretty self-explanatory.
Traditionally, executables that are installed by the system go in /usr/bin. Executables we write, or add, go in /usr/local/bin, and I highly recommend sticking with that.
Some OSes don't automatically supply an entry for /usr/local/bin in the PATH, so you might need to modify your PATH setting in your ~/.bashrc, ~/.bash_profile or ~/.profile to allow the shell to locate the script.
Executable scripts need to have their executable flag set: chmod +x /path/to/executable is the basic command. See man chmod for more information.
I tend to leave the script's extension in place; Ruby scripts are "foo.rb", Python are "bar.py", etc. I do that because I prefer to have that extension as a hint of the language it's written in, but YMMV. The extension isn't necessary so go with what works for you.
Beyond all that, you might want to provide logging output, or output to the system's syslog. In the first case use Ruby's built-in Logger class, or the Syslog class in the second case.
Actually there's two great gems for command line apps in Ruby.
First is methadone which is for simpler command line apps.
Another is gli which is for apps with multiple commands, for example something like bundler.
If you want to know more, you can check out book about creating command line apps build awesome command-line apps in ruby by author of these gems.
You do not need to make it a gem, the following suffices:
Change its name from script.rb to script
Add #!/usr/bin/env ruby as the first line of script
Put it somewhere in PATH (e.g. $HOME/bin, making sure it is in PATH), or execute by giving path explicitly, e.g. $HOME/myscriptdir/script
I am using IRB (interactive ruby console) to learn how to program with Ruby. How do I load a file into the console if I write my programs in a text editor first?
If you only need to load one file into IRB you can invoke it with irb -r ./your_file.rb if it is in the same directory.
This automatically requires the file and allows you to work with it immediately.
Using ruby 1.9.3 on Ubuntu 14.04, I am able to load files from the current directory into irb with the following command line:
irb -I . -r foo.rb
where foo.rb is the file I want to load from my current directory. The -I option is necessary to add the current directory (.) to ruby's load path, as explained in the ruby man page. This makes it possible to require files from the current directory, which is what the -r option to irb accomplishes.
The key piece that wasn't obvious for me when I had this problem is the -I option. Once you do that, you can call require 'foo.rb' from within irb for any files in the current directory. And of course, you can specify any directory you want, not just . with the -I option. To include multiple directories on the load path, separate them with a colon (:), e.g.:
irb -I foo/:bar/:baz/
This command will add the directories foo, bar, and baz to ruby's load path.
The final alternative is to use the relative or absolute path to the file when using require or -r to load a file:
irb -r ./foo.rb
or from within irb:
> require './foo.rb'
Type in irb
And then
require './ruby_file.rb'
This is assuming that ruby_file.rb is in the same directory. Adjust accordingly.
Two ways:
to load source without running the program -- this gives access to all variables and functions:
source("filename.rb")
to run program and then drop into interactive mode -- this only gives access to functions, not variables:
require("filename.rb")
It depends on your ruby. Ruby 1.8 includes your current path, while ruby 1.9 does not. Evaluate $: to determine if your path is included or not. So in ruby 1.9 you must use the entire path, which is always a safe bet.
Then you can use require or load to include the file.
require does not require you to add the suffix of the file when trying to find it and will only include the file once. require should be used instead of load most of the time.
Check out Adding a directory to $LOAD_PATH (Ruby) if you are going to be using ruby 1.8
Type the ruby codes in the text editor
Save it with the extension .rb (for example: demo.rb).
In linux, open your terminal then change directory to the current location of that file (cd command is used to change directory).
After that,type irb and your filename(don't forget to include your extension(.rb)).
In that image,I loaded a simple ruby file which only prints "ruby".
Another way to load the path into irb is just type require then drag and drop the file into the terminal.🙂
-tested using Linux Mint.
For those, who want to load .rb file from the different directory. Just add a string representer of the directory to $: variable.
> $: << "/directory/to/the/required/rb/file"
> require "file"
I've written a data collection script for Cacti in Ruby and it runs fine from the command line but Cacti runs the script via "env -i" which strips the environment so Ruby can't find the rubygems library ("in `require': no such file to load -- rubygems (LoadError)"). How might I work around this?
#!/bin/sh
#export LOAD_PATH=whatever
#export RUBYLIB=whatever
#export RUBYOPT=whatever
#export RUBYPATH=whatever
#export RUBYSHELL=whatever
#export PATH=$PATH:whatever
exec ruby -x. $0 "$#"
#!/usr/bin/ruby
require 'rubygems'
require 'open4' # or whatever
# rest of ruby script here
This is a shell script that runs ruby with -x, which will cause the interpreter to skip lines until it finds #!.*ruby. This will give you a chance to restore the environment. The . after -x is a noop, you can take out the ., or replace it with a directory. Ruby will cd there before running the script.
I'm actually guessing that this is not really what you want, since this could have been done without any trickery by just making two scripts, one for the shell, one for Ruby. Perhaps the list of environment variables Ruby cares about will help...
I don't think $LOAD_PATH used for gems (at least, not exclusively). You might want to look at a couple environment variables that haven't been mentioned here yet:
ENV['GEM_HOME']
ENV['GEM_PATH']
You can see your current paths for gems with:
require 'rubygems'
puts Gem.path
A partial answer might be here: comp.lang.ruby post
Can you modify any of the following in your Ruby script: $:, $-I or $LOAD_PATH? These all just point to the same array which specifies where Ruby looks for classes and other ephemera...
>> $LOAD_PATH
=> ["/usr/local/lib/ruby/site_ruby/1.8", "/usr/local/lib/ruby/site_ruby/1.8/i686-darwin9.5.0", "/usr/local/lib/ruby/site_ruby", "/usr/local/lib/ruby/1.8", "/usr/local/lib/ruby/1.8/i686-darwin9.5.0", "."]
When running ruby scripts as such
ruby some-script.rb
How would I include a file (e.g. configuration file) in it dynamically?
As you have found, the -r option is your friend. It also works with IRB:
irb -ropen-uri
Will do the same as require 'open-uri'
FWIW, the most common thing I need to include via the command line is rubygems. And since newer versions of ruby come with gems built in I don't want to edit the file, but include it for testing. Luckily the folks who created gems added a little alias sugar.
You can do the following:
ruby -rubygems myscript.rb
Instead of the ugly:
ruby -rrubygems myscript.rb
OK, so it is one character, but thought it was extra polish to make me happier.
Actually, I found it. It's the -r command line entry.
-r <library_name>
This causes Ruby to load the library using require.
It is useful when used in conjunction with -n or -p.
You can use:
require 'some_ruby_file'
in some-script.rb. It will load some_ruby_file.rb.
Before you call require "somefile.rb" you must navigate to the folder that the file is located or you must provide the full path. In example: require "~/Documents/Somefolder/somefile.rb"