Ruby: console.log? - ruby

I recently put console.log statements in every line of a JavaScript program and found that it's now much easier to understand. Is there a way to do that with server side code, specifically Ruby? I presume there's no way to read it in firebug, but would it be visible in irb? what console.log equivalent statements would I put in the Ruby code?

puts is the equivalent in ruby.
Example
puts 'Hello World!'

If you are running your server in the console, you can use puts. Otherwise, you will need to write to a file, possibly via a logger (like Rails.logger.info).

Related

Using Ruby to execute arbitrary system calls

This problem is to get into an internship within a devops department:
"Write a ruby library that executes arbitrary system calls (eg: “dmesg", "ping -c 1 www.google.com”) and provides separated output streams of stderr and stdout as well are providing the final return code of the process. Show your work with unit tests.”
Am I supposed to use already established system calls and replicate them in Ruby code? That seems silly to me. Am I supposed to come up with my own arbitrary calls and write a library complete with errors and status calls?
I am not looking for someone to write this for me. I feel that the first step to solving this problem is understanding it.
Get Clarification from the Source
The assignment is poorly worded, and misuses a number of terms. In addition, we can only guess what they really expect; the appropriate thing to do would be to ask the company directly for clarification.
Re-Implement Open3
With that said, what they probably want is a way to process any given command and its arguments as a decorated method, akin to the way Open3#capture3 from the standard library works. That means the code you write should take the command and any arguments as parameters.
For example, using Open3#capture3 from the standard library:
require 'open3'
def command_wrapper cmd, *args
stdout_str, stderr_str, status = Open3.capture3 "#{cmd} #{args.join ' '}"
end
command_wrapper "/bin/echo", "-n", "foo", "bar", "baz"
#=> ["foo bar baz", "", #<Process::Status: pid 31661 exit 0>]
I sincerely doubt that it's useful to re-implement this library, but that certainly seems like what they're asking you to do. Shrug.
You're also supposed to write unit tests for the re-implementation, so you will have to swot something up with a built-in framework like Test::Unit or MiniTest, or an external testing framework like RSpec, or Wrong. See the Ruby Toolbox for a more comprehensive list of available unit testing frameworks.
Luckily for you, Ruby makes it very easy to interact with the underlying operative system.
You can start by reading the documentation for these methods:
Kernel#`
Kernel#system
Kernel#exec
Kernel#spawn
IO#popen
Also, there is the Open3 module from the stdlib.

Running an interactive program from Ruby

I am trying to run gnuplot from ruby (not using an external gem) and parsing its textual output also. I tried IO.popen, PTY.spawn and Open3.popen3 but whenever I try to get the output it just "hangs" -I guess waiting for more output to come. I feel like its somehow done using Thread.new but I couldn't find the correct way to implement it.
Anyone know how it is done?
I guess this is what you want:
require 'pty'
require 'expect'
PTY.spawn('gnuplot') do |input, output, pid|
str = input.expect(/gnuplot>/)
puts str
output.puts "mlqksdf"
str = input.expect(/gnuplot>/)
puts str
output.puts "exit"
end
The problem is that the sub-program is waiting for input that isn't being sent.
Typically, when we call a program that expects input on STDIN, we have to close STDIN, which then signals that program to begin processing. Look through the various Open3 methods and you'll see where stdin.close occurs in many examples, but they don't explain why.
Open3 also includes capture2 and capture3, which make it nice when trying to deal with a program that wants STDIN and you don't have anything to send to it. In both methods, STDIN is immediately closed, and the method returns the STDOUT, STDERR and exit status of the called program.
You need "expect" functionality. Ruby's Pty class includes an expect method.
Creates and managed pseudo terminals (PTYs). See also en.wikipedia.org/wiki/Pseudo_terminal
It's not very well documented though, and doesn't offer a lot of functionality from what I've seen. An example of its use is available at "Using Ruby Expect Library to Reboot Ruckus Wireless Access Points via ssh".
Instead, you might want to look at RubyExpect which is better documented and appears to be current.

Make Ruby console execution more verbose

I want to watch the flow the execution of my ruby code when I am in the console. For example, if I have this :
def process
hash = {a:1,b:2}
hash.values.map!{|e| e+1}
end
And I want to see something like this in console when I type process :
hash = {a:1,b:2}
=> {:a=>1, :b=>2}
hash.values.map!{|e| e+1}
=> [2, 3]
Is there a useful way to do something like this?
$VERBOSE doesn't seems to do anything and $DEBUG seems as the opposite to be too verbose.
You're talking about "trace" functionality.
Some languages, like shell and good-ol' GWBasic, have a flag to show their currently executing line. Ruby's $DEBUG output can flood you with information overload, not so much from your code, but from any gems that look for it and dump their current state or turn on their tracing.
Many people sprinkle their code with puts to have it show some indicator of where they are, during their development/testing. If you do that, I'd recommend writing it as a method to bottleneck your output and let you easily turn it on/off. Also, use a flag to check whether you want to debug. You might even want to use OptionParser to let you create a --debug flag to pass on the command-line. Another nice side-effect of using a method is it's easy to redirect the output to a file you can tail and watch the output as it occurs, and later use for triage.
Another alternative is to load the code into the debugger and tell it to trace. You'll see every step of the code, which is very verbose, but the detail is good. You can also tell it to run to certain points so you can poke at the code and dig around, dropping into IRB if needed.
Personally, being old-school and having cut my teeth on assembly-language, I'm comfortable in debuggers, so I use Ruby's a lot. It's easy to tell it to run to a certain spot and stop, or you can embed include 'debugger'; debugger into your code and it'll stop at that point. Once there, it's possible to see what's going on, then c to continue, and let the program run until it hits the debugger statement again. I find the debugger to be very powerful and a nice selective magnifying glass for those times I want to know what's going on.
"Debugging in Ruby" has lots of nice tips you might find useful too.
EDIT:
I like Alex D's suggestion to look into Ruby's set_trace_func. I haven't used it (and, frankly forgot about it), but that'd be a good way to set up a nice trace in an app. With a little code you could set up toggling it on/off and selectively outputting given a certain class or condition since you're in control of the proc being called.
One option would be to use set_trace_func (http://apidock.com/ruby/Kernel/set_trace_func) to set up a hook which will print out each line as it is executed. Be aware that may overwhelm you with a bunch of information on the internals of irb.
Another option would be to dig into the source code for irb and add an option to print each line as it is executed.
Have you tried the pry gem? Put require 'pry'; binding.pry inside your code and run your script. You will have a ruby console just where your put it. Maybe that is what you are looking for.
Otherwise you should take a look at a ruby debugger.

Is calling puts without arguments bad practice?

Below is a small screenshot from within RubyMine 3.1. I am just starting to learn Ruby. The code here is from the Presenter-First MVP C# code generator over at atomicobject.com.
I am using this project along with a book to learn Ruby. The documentation for puts shows that it expects at least one parameter. Yet this code appears "somewhat legal" for two reasons:
The code appears to work fine when I
step thru it via the debugger.
Searching online, and even here at SO, shows that puts w/o arguments creates a newline.
However, is it bad practice to do this (hence the RubyMine warning)? The code I am looking at is from 2006. I'm running it with Ruby 1.9.2 if that matters any.
This is perfectly fine, as puts provides 'default' value for the first parameter:
def puts(obj='', *arg)
As for RubyMine, it doesn't show any errors for me. May it happen that you define method puts somewhere else in your code? You can cmd+click on it, to get to the definition.
Anyway, if you're able to reproduce problem in a clean new project, you can freely submit a bug report to JetBrains.
No, it can be helpful to create the physical line break in your source as well as the output, and like you have seen already, puts is perfectly capable of accepting zero arguments.
Personally, if I'm creating a multi-line output I prefer to use here-doc syntax.

What is best way to execute a Ruby program from a Ruby program?

I would like to do something like this from a Ruby script, within a loop:
Write a file a.rb (which changes each iteration)
execute system(ruby 'a.rb')
a.rb writes a string with results to a file 'results'
a.rb finishes and Ruby returns 'true' (assuming no errors)
the calling script reads the file 'results' and takes action.
I expect there are many better ways of doing this. For example, instead of step #2-#5 could I
simply load 'a.rb' (within the loop) and invoke one one of its methods? Is there a better way by using eval() or something else? (Gaining an understanding of metaprogramming is on my Ruby to-do list.)
I think eval is probably the right solution for dynamically-generated code; that's what it's designed for. Instead of creating a.rb at all, just eval('some-code-that-would-be-in-a.rb').

Resources