Ruby on Windows: Require is not recognized as an internal or external command - ruby

I'm trying to use Guard to monitor changes in AsciiDoctor file. Here is Guardfile from official docs:
require 'asciidoctor'
guard 'shell' do
watch(/^mydoc\.adoc$/) {|m|
Asciidoctor.convert_file m[0]
}
end
It works for me. But now, I'm trying to launch the same things without creating Guardfile - i.e. I want simply write these commands in Windows cmd.exe.
But when I write require 'asciidoctor' command prompt gives me an error:
'require' is not recognized as an internal or external command, operable program or batch file.
Well, I know that such error messages are often have something with Windows %Path% environment variable. But I don't understand how to fix it in this particular case.

Ruby and DOS Batch are two completely different programming languages that have absolutely nothing to do with each other. You simply cannot expect an interpreter for DOS Batch to be able to run Ruby code and vice versa. (Especially considering that Ruby didn't even exist when CMD.EXE was written, so how could CMD.EXE possibly know how to interpret Ruby code?)
You need to run Ruby code in a Ruby interpreter (or use a Ruby compiler to compile it to something that you have an interpreter for).

Related

windows command not responding to ruby - trying to call a macro with a .mac file extension

I have a macro file that i can run in the cmd line in windows by simply navigating to the directory and typing profit.mac in the cmd line
however, when i go to call it in a ruby script i keep getting errors
I have tried system(), exec(), ``, and %x() and i havent been able to get it to work
are there any other options I have to call my macro file?
i get the same error on 3/4 of them
(backticks), profit.mac = (Errno::ENOEXEC)
exec('profit.mac') = (Errno::ENOEXEC)
%x('profit.mac') = (Errno::ENOEXEC)
system('profit.mac') = nothing happens
Are your .mac macros files executables or need to be interpreted by another program?
I guess those macros files have to be interpreted by another "macros executor" program. You would need to prepend that in your command execution.
exec('macrosInterpreter.exe /path/to/profit.mac')
It is like running a ruby script. Assume you want to run a test.rb file. You can't do exec('test.rb'), you would have to do exec('ruby test.rb').

what is the use of "#!/usr/local/bin/ruby -w" at the start of a ruby program

what is the use of writing the following command at the start of a ruby program ?
#!/usr/local/bin/ruby -w
Is it OS specific command? Is it valid for ruby on windows ? if not, then what is an equivalent command in windows ?
It is called a Shebang. It tells the program loader what command to use to execute the file. So when you run ./myscript.rb, it actually translates to /usr/local/bin/ruby -w ./myscript.rb.
Windows uses file associations for the same purpose; the shebang line has no effect (edit: see FMc's answer) but causes no harm either.
A portable way (working, say, under Cygwin and RVM) would be:
#!/usr/bin/env ruby
This will use the env command to figure out where the Ruby interpreter is, and run it.
Edit: apparently, precisely Cygwin will misbehave with /usr/bin/env ruby -w and try to look up ruby -w instead of ruby. You might want to put the effect of -w into the script itself.
The Shebang line is optional, and if you run the ruby interpreter and pass the script to it as a command line argument, then the flags you set on the command line are the flags ruby runs with.
A Shebang line is not ruby at all (unless you want to call it a ruby comment). It's really shell scripting. Most linux and unix users are running the BASH shell (stands for Borne Again SHell), but pretty much every OS has a command interpreter that will honor the Shebang.
“#!/usr/local/bin/ruby -w”
The "she" part is the octothorp (#), aka pound sign, number sign, hash mark, and now hash tag (I still call it tic-tac-toe just cuz).
The "bang" part is the exclaimation mark (!), and it's like banging your fist on the table to exclaim the command.
On Windows, the "Shell" is the command prompt, but even without a black DOS window, the command interpreter will run the script based on file associations. It doesn't really matter if the command interpreter or the programming langue is reading the shebang and making sure the flags are honored, the important point is, they are honored.
The "-w" is a flag. Basically it's an instruction for ruby to follow when it runs the script. In this case "-w" turns on warnings, so you'll get extra warnings (script keeps running) or errors (script stops running) during the execution of the script. Warnings and exceptions can be caught and acted upon during the program. These help programmers find problems that lead to unexpected behavior.
I'm a fan of quick and dirty scripts to get a job done, so no -w. I'm also a fan of high quality reusable coding, so definitely use -w. The right tool for the right job. If you're learning, then always use -w. When you know what you're doing, and stop using -w on quick tasks, you'll start to figure out when it would have helped to use -w instead of spending hours trouble shooting. (Hint, when the cause of a problem isn't pretty obvious, just add -w and run it to see what you get).
"-w" requires some extra coding to make it clear to ruby what you mean, so it doesn't immediately solve things, but if you already write code with -w, then you won't have much trouble adding the necessary bits to make a small script run with warnings. In fact, if you're used to using -w, you're probably already writing code that way and -w won't change anything unless you've forgotten something. Ruby requires far less "plumbing code" then most (maybe all) compiled languages like C++, so choosing to not use -w doesn't allow you to save much typing, it just lets you think less before you try running the script (IMHO).
-v is verbose mode, and does NOT change the running of the script (no warnings are raised, no stopping the script in new places). Several sites and discussions call -w verbose mode, but -w is warning mode and it changes the execution of the script.
Although the execution behavior of a shebang line does not translate directly to the Windows world, the flags included on that line (for example the -w in your question) do affect the running Ruby script.
Example 1 on a Windows machine:
#!/usr/local/bin/ruby -w
puts $VERBOSE # true
Example 2 on a Windows machine:
#!/usr/local/bin/ruby
puts $VERBOSE # false

Execute ruby script without .rb extension?

I know you can execute a script without typing "ruby" before the file name if you add a shebang, but how do you execute it without a file extension so instead of "filename.rb" you can use just "filename".
And, what's the norm/best-practice for deploying Ruby programs, i.e. file location and path etc.?
In linux, the information about the interpreter is usually taken from the shebang line, not from the extension. That's why you basically don't need the extension (but usually need the execute bit in the file attributes).
I don't know what are the traditions in Ruby about file naming (is it considered a good thing or not to include an extension), but it's generally a good idea to follow it (whatever it is).

Calling ruby script from groovy

I have a groovy script and I need to call a ruby script.
I would like to pass arguments to Ruby script and would like to capture the output from Ruby script to use it in Groovy Script. Can somebody suggest how I can do this? I tried Process.execute(). It works for other dos commands but not for cmd /c ruby test.rb.
Since a ruby file isn't a batch file you don't need to use cmd to execute it. You could do
Process.execute("ruby.exe test.rb")
Assuming ruby.exe is on your path. Another option depending on your requirements may be to use JRuby which will allow you to run ruby code on the JVm and integrate nicely with Groovy.

For ruby/webrick, I need windows to recognize shebang (#!) notation

(Bear with me, I promise this gets to shebang and windows.)
I have about the simplest of WEBRick servers put together:
require 'webrick'
include WEBrick
s = HTTPServer.new(:Port=>2000, :DocumentRoot=>Dir::pwd)
s.start
Couldn't be simpler. This basic server does accept http connections (firefox, internet exploder, wget, TELENT) and deals with them appropriately, as long as I'm just fetching static documents. If, however, I set one of the files in the directory to have a .cgi extension, I get a 500 back and the following on the server's terminal:
ERROR CGIHandler: c:/rubyCGI/test.cgi:
C:/...[snip]...webrick/httpservlet/cgi_runner.rb:45: in 'exec': Exec format error - ...[snip]...
I've done a few things on the command line to mimic what is going on in line 45 of cgi_runner.rb
c:\>ruby
exec "c:/rubyCGI/test.cgi"
^Z
(same error erupts)
c:\>ruby
exec "ruby c:/rubyCGI/test.cgi"
^Z
Content-type: text/html
Mares eat oats and does eat oats and I'll be home for Christmas.
Clearly, WEBrick hasn't been cleared for landing on windows. Your usual headaches of corporate paranoia prevent me from modifying webrick, so can I get the shebang notation in c:/rubyCGI/test.cgi recognized by the OS (windows) so I don't have to explicitly tell it each time which interpreter to use? I could assign all .cgi files to be associated with ruby, but that would be limiting in the long run.
UPDATE:
Since posting this, it has occurred to me that it may not be possible at all to run a cgi web server from ruby; ruby has no forking support. With no ability to fork a process, a cgi server would have to execute each cgi script one-at-a-time, neglecting all concurrent requests while the first one completed. While this may be acceptable for some, it would not work for my application. Nevertheless, I would still be very interested in an answer to my original question—that of getting shebang working under windows.
I think what you want is to associate the file extension with Ruby. I don't think it's possible to get the !# notation to work on Windows but it is possible to get Windows to automatically launch a script with a particular interpreter (as in your second example). A good step by step discussion of what you'd want to do is here. You specifically want the section headed: "To create file associations for unassociated file types". I think that will accomplish what you're trying to do.
A generic solution that works for both Ruby 1.8.6.pxxx and 1.9.1.p0 on
Windows is the following:
Edit the file: c:\ruby\lib\ruby\1.9.1\webrick\httpservlet\cgi_runner.rb
Add the following lines at the top of the file:
if "1.9.1" == RUBY_VERSION
require 'rbconfig' #constants telling where Ruby runs from
end
Now, locate the last line where is says: exec ENV["SCRIPT_FILENAME"]
Comment that line out and add the following code:
# --- from here ---
if "1.9.1" == RUBY_VERSION #use RbConfig
Ruby = File::join(RbConfig::CONFIG['bindir'],
RbConfig::CONFIG['ruby_install_name'])
Ruby << RbConfig::CONFIG['EXEEXT']
else # use ::Config
Ruby = File::join(::Config::CONFIG['bindir'],
::Config::CONFIG['ruby_install_name'])
Ruby << ::Config::CONFIG['EXEEXT']
end
if /mswin|bccwin|mingw/ =~ RUBY_PLATFORM
exec "#{Ruby}", ENV["SCRIPT_FILENAME"]
else
exec ENV["SCRIPT_FILENAME"]
end
# --- to here ---
Save the file and restart the webrick server.
Explanation:
This code just builds a variable 'Ruby' with the full path to
"ruby.exe", and
(if you're running on Windows) it passes the additional parameter
"c:\ruby\bin\ruby.exe" , to the Kernel.exec() method, so that your
script can be executed.
Not really to argue... but why bother webrick when mongrel is much faster and with native compiled with windows? And of coz, that means no shebang is needed.
Actually, it is possible to get Windows to recognize shebang notation in script files. It can be done in a relatively short script in say, Ruby or AutoIt. Only a rather simple parser for the first line of a script file is required, along with some file manipulation. I have done this a couple times when either cross-compatibilty of script files was required or when Windows file extensions did not suffice.

Resources