I recently converted a ruby library to a gem, which seemed to break the command line usability
Worked fine as a library
$ ruby -r foobar -e 'p FooBar.question' # => "answer"
And as a gem, irb knows how to require a gem from command-line switches
$ irb -rubygems -r foobar
irb(main):001:0> FooBar.question # => "answer"
But the same fails for ruby itself:
$ ruby -rubygems -r foobar -e 'p FooBar.question'
ruby: no such file to load -- foobar (LoadError)
must I now do this, which seems ugly:
ruby -rubygems -e 'require "foobar"; p FooBar.question' # => "answer"
Or is there a way to make the 2 switches work?
Note: I know the gem could add a bin/program for every useful method but I don't like to pollute the command line namespace unnecessarily
Ruby script arguments are passed to the Ruby program by the shell, the program that accepts commands (such as bash) on the terminal. On the command-line, any text following the name of the script is considered a command-line argument.
Press Ctrl twice to invoke the Run Anything popup. Type the ruby script. rb command and press Enter . If necessary, you can specify the required command-line options and script arguments.
The “verbose” mode of the ruby interpreter is activated by one of the following command-line flags: -v – also prints the ruby version before running the program. -w or --verbose. -W <level> – the level can be one of 0, 1, and 2 (more info below) -d – turns on both verbose and debugging mode.
Open up IRB (which stands for Interactive Ruby). If you're using macOS open up Terminal and type irb , then hit enter. If you're using Linux, open up a shell and type irb and hit enter. If you're using Windows, open Interactive Ruby from the Ruby section of your Start Menu.
-rubygems is actually the same as -r ubygems.
It doesn't mess with your search path, as far as I understand, but I think it doesn't add anything to your -r search path either. I was able to do something like this:
ruby -rubygems -r /usr/lib/ruby/gems/myhelpfulclass-0.0.1/lib/MyHelpfulClass -e "puts MyHelpfulClass"
MyHelpfulClass.rb exists in the lib directory specified above.
That kind of sucks, but it at least demonstrates that you can have multiple -r equire directives.
As a slightly less ugly workaround, you can add additional items to the ruby library search path (colon delimited in *nix, semicolon delimited in windows).
export RUBYLIB=/usr/lib/ruby/gems/1.8/gems/myhelpfulclass-0.0.1/lib
ruby -rubygems -r MyHelpfulClass -e "puts MyHelpfulClass"
If you don't want to mess with the environment variable, you can add something to the load path yourself:
ruby -I /usr/lib/ruby/gems/1.8/gems/myhelpfulclass-0.0.1/lib \
-rubygems -r MyHelpfulClass -e "puts MyHelpfulClass"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With