I have using Webrick + CGI and when I instantiate, returns an error: (offline mode: enter name=value pairs on standard input)
irb(main):001:0> require 'cgi'
=> true
irb(main):002:0> cgi = CGI.new
(offline mode: enter name=value pairs on standard input)
Nope, not an error. That's the way it works.
From the ruby-docs CGI documentation
If the CGI object is not created in a standard CGI call environment (that is, it can’t locate REQUEST_METHOD in its environment), then it will run in “offline” mode. In this mode, it reads its parameters from the command line or (failing that) from standard input
In the irb console, after the (offline mode: enter name=value pairs on standard input) message, the console is waiting for you to enter the values. Enter key value pairs followed by Ctrld to finish entering data.
irb(main):001:0> require 'cgi'
=> true
irb(main):002:0> cgi = CGI.new
(offline mode: enter name=value pairs on standard input)
name=Prakash
number=432
Ctrld
=> #<CGI:0x007fa4eb2abd30 #options={:accept_charset=>"UTF-8"}, #accept_charset="UTF-8", #multipart=false, #params={"name"=>["Prakash"], "number"=>["432"]}, #cookies={}, #output_cookies=nil, #output_hidden=nil>
irb(main):003:0>
Refer to CGI Programming Documentation on PLEAC-Ruby for further code examples of working with CGI in ruby.
Related
I am running the command bundle install and keep getting the following error
Please CGI escape your usernames and passwords before setting them for authentication.
I am unsure how I could go about CGI escaping my credentials- any ideas? Thanks
You can do this in irb with Ruby's CGI::Util module:
$ irb
irb(main):001:0> require "cgi"
=> true
irb(main):002:0> CGI.escape "foo#example.com"
=> "foo%40example.com"
I'm experiencing an issue wherein awesome_print is not displaying output in it's gorgeous colorized multiline format. What I find most curious is that while the gem is installed:
$ gem install awesome_print
Successfully installed awesome_print-1.6.1
1 gem installed
It returns a false upon require in IRB:
>> require 'awesome_print'
false
Any idea as to what may be causing this? I am not quite sure how to tackle this since gem installation seems to work fine and I can even use ap "test" in IRB with no error, except there is no colorization or proper printing with multiple lines and seems to simply fall back to some other method for printing.
No ~/.aprc changes evoke any changes either.
Pass the options ap object, options = {:plain => false, :multiline => true} or you can add it to the config file.
create an ~/.irbc file with the following content
require "awesome_print"
AwesomePrint.irb!
:multiline => true, # Display in multiple lines.
:plain => false
I had the same error,although require was returning false but awesome print was working, try to print something using awesome_print(ap), like
ap data = {foo: "bar"}
I'm facing a problem when I run my program in a browser with the WEBrick server. It shows me my code as written in the 2loop.rb file.
When I run ruby -run -e -httpd. -p 5000 at the command prompt, and load http://localhost:5000/2loop.rb in the browser, it shows the code from 2loop.rb instead of running it.
How can I execute the 2loop.rb program instead?
TL;DR
You're doing this to yourself by serving your current working directory as the root of your web server. You aren't actually running the code in your file; you're just telling WEBrick to serve any file you name in the URI. http://localhost:5000/2loop.rb will serve "2loop.rb" as text/html in your posted example.
Using un.rb
The flag you're using isn't actually "run." Instead, the -r flag actually loads a module, which in this case is the un.rb module. Using un.rb to start WEBrick is done like this:
$ ruby -run -e httpd . -p 5000
and starts a web server in the document root. In this case, the dot means to use the current working directory as the root. This is not really what you want to start code you've placed inside a Ruby file.
Running WEBrick Programmatically
Using some snippets from the WEBrick documentation, you will see that you can create a file named "2loop.rb" containing the following:
#!/usr/bin/env ruby
require 'webrick'
root = File.path '/tmp/public_html'
server = WEBrick::HTTPServer.new :Port => 5000, :DocumentRoot => root
trap 'INT' do server.shutdown end
server.start
This will serve files out of the /tmp/public_html directory on port 5000, which you can reach at http://localhost:5000. You can then make the file executable and start the server with ./2loop.rb, or just run ruby 2loop.rb if you don't want to make your file executable for some reason.
If you don't want WEBrick just to serve files, you will have to add custom behavior to your web server inside the 2loop.rb script. This is a fairly low-level thing to do, but may suit your needs.
Sensible Alternatives
You should probably use a web framework like Ruby on Rails or Sinatra if you don't want to have write all the low-level behaviors yourself. Sinatra in particular is a very lightweight alternative. This example:
#!/usr/bin/env ruby
require 'sinatra'
set :port, 5000
get '/hello' do
"Hello, World!"
end
will create a URL at http://localhost:5000/hello with a custom action that returns "Hello, World!" as an in-browser response.
Well, I'd suggest you to use Common Gateway Interface (CGI). Let me provide you an example.
Firstly, create a file named server.rb:
require 'webrick'
server = WEBrick::HTTPServer.new(
:Port => 6789, # a server's port
:DocumentRoot => File.join(Dir.pwd, "/scripts") # a folder with scripts
)
server.start
Secondly, create a folder scripts and put the following file (the_best_program.cgi) into it. Note the .cgi extension. It matters. Look here for details on the first line of the script (shebang) if you are working under Windows.
#!/usr/bin/env ruby
require 'cgi'
print "Content-type: text/plain\n\n"
5.times { |i| puts "Hello world #{i}!"}
puts 'So many worlds there. :('
Finally,
Launch your server from command-line (ruby server.rb).
Start browser and go to localhost:6789/the_best_program.cgi (or 0.0.0.0:6789/the_best_program.cgi)
Enjoy!
Notes
You might need to change permissions to your scripts folder / script. On unix-like system do: chmod 755 scripts scripts/the_best_program.cgi.
You can launch not only ruby scripts this way.
I'm new to programming. Just about to start learning Ruby. I already took a console class, but I am stuck here.
I'm using a mac 10.6.8. I have done a quick 1+2 in the sublime text editor. I saved it. I went over to my console typed irb and then typed ruby example.rb. I have read elsewhere here that typing require './example' would help....it didn't. I am getting the following
NameError: undefined local variable or method `example' for main:Object
from (irb):2
from /usr/local/rvm/rubies/ruby-1.9.3-p392/bin/irb:16:in `<main>'
I don't understand what I am doing wrong. Thank you for your help. I really appreciate it.
-L
I would do as below:
kirti#kirti-Aspire-5733Z:~$ irb
2.0.0p0 :001 > require 'fileutils'
=> true
2.0.0p0 :002 > FileUtils.pwd
=> "/home/kirti"
2.0.0p0 :003 > FileUtils.cd "/home/kirti/ruby"
=> nil
2.0.0p0 :004 > load "./SO.rb"
3
=> true
2.0.0p0 :005 > require "./SO.rb"
3
=> true
My SO.rb file contains the below line :
puts 1+2
May be you wanna give a try.
Step 1: Navigate to your project/file folder by using command "cd folder_name/folder_location"
Step 2: load './example.rb'
For better solution you may wanna define some function inside example.rb
Like:
def sum
1 + 2
end
And to get the output enter sum in irb after loading the example.rb file.
irb is the interactive ruby shell. Within the shell, everything you type is interpreted as Ruby code, not bash commands. So, for example:
bash> puts 1 + 2
# command not found: puts
# this happens because you're not in a Ruby shell
bash> irb
# now you're in a Ruby shell
irb> puts 1 + 2
# 3
If you wrote some code in example.rb, you have two options:
From the bash shell, run ruby example.rb (from the same directory where your example.rb file is saved.
From the irb console, you can require 'example', which will load the contents of example.rb into your interpreter. In this case, it will immediately execute the Ruby code. If you wrapped the contents of example.rb in a class, it would load the class, but not execute code within it until you instantiated/called it.
Hopefully that helps!
My guess is that you are typing (into irb):
require example.rb
When you need to type:
require './example.rb'
The first tells ruby: "require what is in a variable called example". Because you did not define a variable called example, it results in the no variable or method error.
The second tells ruby: "require a string './example.rb'". Since the require method essentially knows how to find the file name passed as a string and evaluate the file, you'll get the right output
By the way, for this example, example.rb needs to be in the same directory. If example.rb is in another directory, you'll need to use the full path (I won't expand on it here) to source it.
You'll also notice that the output will look something like this:
3
=> true
This is because the file was evaluated (executing the code: puts 1+2) and the require method returns true to indicate it evaluated the file.
If you require the file again, you'll get false because the file is already loaded.
I have experienced some ODD behavior from the code below:
require 'CSV'
$DEBUG = ARGV.empty? ? false : ARGV[0] #Global debug flag.
class PhoneBook
#class code here etc etc
end
PhoneBook.start_dir = "file-io-samples/phonebooks/"
puts "Enter a phonebook!"
name = gets #This is the problem.
puts "Using #{name}.."
When I pass true to have $DEBUG set to true on execution I get an error from name = gets and I have no idea why. If I don't pass parameters via the command line everything works fine.
This is the error output:
C:\Pickaxe>ruby PhoneBook.rb
Enter a phonebook!
Hurrah! Works
Using Hurrah! Works
..
C:\Pickaxe>ruby PhoneBook.rb true
Enter a phonebook!
Exception `Errno::ENOENT' at PhoneBook.rb:62 - No such file or directory - true
PhoneBook.rb:62:in `gets': No such file or directory - true (Errno::ENOENT)
from PhoneBook.rb:62:in `gets'
from PhoneBook.rb:62:in `<main>'
C:\Pickaxe>
If I need to I can post the class definition, but I don't think it's part of the problem.
gets reads from stdin if no arguments are passed, and from the file that was passed as an argument otherwise. You are passing an argument true, ergo gets tries to read from a file named true, which apparently doesn't exist.
This is the very first sentence of the documentation of gets:
Returns (and assigns to $_) the next line from the list of files in ARGV (or $*)
This wouldn't cause a problem on *nix, but I expect Windows, or Ruby on Windows, isn't handling the additional command-line parameter the same way. On *nix, we can use -- between the script name and the parameter to tell the OS not to pass the parameter as a flag. In other words, Ruby wouldn't see true, your script would.
ruby some_script.rb -- options
But, in general, I think you're doing it wrong and recommend handling your command-line options in a standard way by using the OptionParser class:
require 'optparse'
OptionParser.new do |opt|
opt.on('-d', '--[no-]debug') { |o| $DEBUG = o }
end.parse!
puts $DEBUG
Running that several times on my Mac OS system, with different parameters, gives me:
$ ruby test.rb
false
$ ruby test.rb --no-debug
false
$ ruby test.rb -d
true
$ ruby test.rb --debug
true
You might still have to use -- to tell the OS and called app which parameters belong to what.