How to call ruby class from Groovy class and execute it from groovy class - ruby

I wrote a ruby class which has print statement. Then i wrote a Groovy class which invokes this ruby class and executes
I tried like Process.execute("ruby.exe test.rb")
Ruby code-->
class Test
puts "hello, I am ruby"
end
Groovy code-->
class TestGroovy {
static main(String[] args) {
Process.execute("ruby.exe test.rb")
}
}
i need to get output as hello, I am ruby when i run TestGroovy.

From the docs:
Groovy provides a simple way to execute command line processes. Simply write the command line as a string and call the execute() method. E.g., on a *nix machine (or a windows machine with appropriate *nix commands installed), you can execute this:
def process = "ls -l".execute() // <1>
println "Found text ${process.text}" // <2>
executes the ls command in an external process
consume the output of the command and retrieve the tex

You can execute Ruby code from Groovy or Java code using a JSR-223 script engine. Here is an example Groovy script:
#Grab('org.jruby:jruby:9.2.5.0')
import javax.script.ScriptEngine
import javax.script.ScriptEngineManager
ScriptEngine engine = new ScriptEngineManager().getEngineByName('jruby')
engine.eval('puts "Hello world!"')
eval() also accepts a java.io.Reader which you could get from your file path. There are lots more details on ways to run Ruby from Java/Groovy here: https://github.com/jruby/jruby/wiki/RedBridge

Related

Groovy script can't execute() external process

Main question: Would groovy's execute() method allow me to run a command that takes a file as an argument, any maybe run the command in background mode?
Here is my issue. I was able to use groovy's execute() for simple commands like ls for example. Suppose now I want to start a process like Kafka from a groovy script (end result is to replace bash files with groovy scripts). So I start with these lines:
def kafkaHome = "Users/mememe/kafka_2.11-0.9.0.1"
def zkStart = "$kafkaHome/bin/zookeeper-server-start.sh"
def zkPropsFile = "$kafkaHome/config/zookeeper.properties"
Now, executing the command below form my mac terminal:
/Users/mememe/kafka_2.11-0.9.0.1/bin/zookeeper-server-start.sh /Users/mememe/kafka_2.11-0.9.0.1/config/zookeeper.properties
starts up the the process just fine. And, executing this statement:
println "$zkStart $zkPropsFile"
prints the above command line as is. However, executing this command from within the groovy script:
println "$zkStart $zkPropsFile".execute().text
simply hangs! And trying this:
println "$zkStart $zkPropsFile &".execute().text
where I make it a background process goes further, but starts complaining about the input file and throws this exception:
java.lang.NumberFormatException: For input string: "/Users/mememe/kafka_2.11-0.9.0.1/config/zookeeper.properties"
Trying this gives the same exception as above:
def proc = ["$zkStart", "$zkPropsFile", "&"].execute()
println proc.text
What am I missing please? Thank you.
Yes, try using the consumeProcessOutpusStream() method:
def os = new File("/some/path/toyour/file.log").newOutputStream()
"$zkStart $zkPropsFile".execute().consumeProcessOutputStream(os)
You can find the the method in the Groovy docs for the Process class:
http://docs.groovy-lang.org/docs/groovy-1.7.2/html/groovy-jdk/java/lang/Process.html
Which states:
Gets the output and error streams from a process and reads them to keep the process from blocking due to a full output buffer. The stream data is thrown away but blocking due to a full output buffer is avoided. Use this method if you don't care about the standard or error output and just want the process to run silently - use carefully however, because since the stream data is thrown away, it might be difficult to track down when something goes wrong. For this, two Threads are started, so this method will return immediately.

Ruby + Cucumber: How to execute cucumber in code?

I'd like to execute Cucumber features from within Ruby code.
Typically the cucumber binary installed with the gem is executed on the command line with one or more features specified.
However, I'd like to define logic that creates a dynamic feature execution flow. In other words, the program can work out which features should be executed.
Is it possible to instantiate Cucumber with specified feature files from Ruby code as opposed to the command line?
I discovered how from the mailing list and some API reading.
features="path/to/first.feature path/to/second.feature"
runtime = Cucumber::Runtime.new
runtime.load_programming_language('rb')
Cucumber::Cli::Main.new([features]).execute!(runtime)
If you want all features within your gem's features/ directory to be executed, pass an empty array to Main.new instead.
To convert this example command, with features and options specified:
cucumber features/first.feature features/second.feature -d -f Cucumber::Formatter::Custom
into Ruby code, it boils down to passing Cucumber an args array:
require 'cucumber'
# Method 1 - hardcoded features
args = %w(features/first.feature features/second.feature -d -f Cucumber::Formatter::Custom)
# Method 2 - dynamic features
features = 'features/first.feature features/second.feature'
args = features.split.concat %w(-d -f Cucumber::Formatter::Custom)
# Run cucumber
begin
Cucumber::Cli::Main.new(args).execute!
rescue SystemExit
puts "Cucumber calls #kernel.exit(), killing your script unless you rescue"
end
Tested using Ruby 2.0.0p598 and Cucumber 1.3.17

Call ruby function from command-line

How can I directly call a ruby function from the command-line?
Imagine, I would have this script test.rb:
class TestClass
def self.test_function(some_var)
puts "I got the following variable: #{some_var}"
end
end
If this script is run from the command-line (ruby test.rb), nothing happens (as intended).
Is there something like ruby test.rb TestClass.test_function('someTextString')?
I want to get the following output: I got the following variable: someTextString.
First the name of the class needs to start with a capital letter, and since you really want to use a static method, the function name definition needs to start with self..
class TestClass
def self.test_function(someVar)
puts "I got the following variable: " + someVar
end
end
Then to invoke that from the command line you can do:
ruby -r "./test.rb" -e "TestClass.test_function 'hi'"
If you instead had test_function as an instance method, you'd have:
class TestClass
def test_function(someVar)
puts "I got the following variable: " + someVar
end
end
then you'd invoke it with:
ruby -r "./test.rb" -e "TestClass.new.test_function 'hi'"
Here's another variation, if you find that typing ruby syntax at the command line is awkward and you really just want to pass args to ruby. Here's test.rb:
#!/usr/bin/env ruby
class TestClass
def self.test_function(some_var)
puts "I got the following variable: #{some_var}"
end
end
TestClass.test_function(ARGV[0])
Make test.rb executable and run it like this:
./test.rb "Some Value"
Or run it like this:
ruby test.rb "Some Value"
This works because ruby automatically sets the ARGV array to the arguments passed to the script. You could use ARGV[0] or ARGV.first to get the first argument, or you could combine the args into a single string, separated by spaces, using ARGV.join(' ').
If you're doing lots of command-line stuff, you may eventually have a use for Shellwords, which is in the standard ruby lib.
If you have multiple arguments to call in a example like this:
class TestClass
def self.test_function(some_var1, some_var2)
puts "I got the following variables: #{some_var1}, #{some_var2}"
end
end
run it like this (the arguments need to be comma separated in this case)
ruby -r "./test.rb" -e "TestClass.new.test_function 'hi','Mike'"
#!/usr/bin/env ruby
class A
def run
p :Hello_world
end
self
end.new.run
The usual way to script Ruby is to just use the top level execution environment called main. You can just start defining methods and code you write outside of a class, and these will be executed directly. (BTW, code inside a class but outside any method will run "by itself" also.)
Anyway, I'm with you ... I like writing all code in a named class and instantiating that class, so you can combine the techniques .. have the class return its own object .. and then use just a little of that top level code to allocate, initialize, and then dot into the class.
With this, you can just type $ ruby test.rb and it will do what you want. Or you can chmod +x test.rb; ./test.rb since we did add a shebang.
If you are working on a command line interface, then I would suggest to have a look at thor.
Thor directly maps your commands to methods within the defined class, see the thor wiki for an example.
Just an extension to Ingenu's answer for the case that the function does not print something out, but does return something.
We would have the following test.rb
class TestClass
def self.test_function(some_var)
return "I got the following variable: " + some_var
end
end
Then to invoke that from the command line and get the return value:
ruby -r "./test.rb" -e "puts TestClass.test_function('hi')"
If you know that how to call an rb file from commandline
ruby yourfile.rb
This can do the whole trick for you.
What you have done is, just defined your methods in the class. Now you can call it below the definition. If you still want to read, wide open your eyes
class TestClass
def self.test_function(some_var)
puts "I got the following variable: #{some_var}"
end
test_function(var)
end

Testing pure Ruby bin/my_app.rb application with RSpec?

I have a command line (NON-RAILS) application written in pure Ruby that I'm driving out through Cucumber and RSpec. It follows the typical application hierarchy of lib, bin, spec, and feature directories.
Up until now, I've followed the traditional process of writing a failing Cucumber feature/scenario, dropping down to RSpec to drive out the supporting lib files, then getting the scenario to pass.
Unfortunately, this doesn't seem to be as straight forward when driving out the main application entry point in "bin/my_application.rb". The main issue for me is that I'm not describing a class in RSpec, it's a sequential Ruby script for managing the application's classes and initialization via command line parameters and options.
"bin/my_application.rb" is just a small shell-executed wrapper for parsing command line options and passing them onto my main application class as initializer options. I'd still like to test the behavior of the bin script (e.g. MyApp.should_receive(option_a).with(parameter)).
Any suggestions/thoughts/advice? Is this a normal test strategy for driving out command line Ruby script behavior?
Thanks in advance.
Not sure I fully comprehend what you're asking, but I'd say that if you want to use RSpec to test your parameter passing it should be easy enough to do. Say you have your wrapper script:
# my_application.rb
command = Command.new
command.foo = true if ARGV[0]
command.bar = true if ARGV[1]
command.baz = false if ARGV[2]
command.make_dollars(1000000)
Just mix it up and make it a class suitable for testing.
# command_runner.rb
class CommandRunner
def run(args, command = Command.new)
command.foo = true if args[0]
command.bar = true if args[1]
command.baz = false if args[2]
command.make_dollars(1000000)
end
end
# my_application.rb
CommandRunner.new.run(ARGV)
Now the only thing you don't have tested is your default parameter on the run command and the one line in the file my_application.rb
Hope that helps.
Brandon

Why can't I do a method call after a #Grab declaration in a Groovy script?

I'm trying to build a DSL and using a Global AST Transform to do it. The script is compiling with groovyc fine, but I'd like to be able to be able to have a user use Grab/Grape to pull the JAR and just have it execute right away as a groovy script.
I then found that I couldn't do it correctly because there's a parsing error in the script if there isn't a method declaration or import statement after the #Grab call.
Here's an example:
#Grab(group='mysql', module='mysql-connector-java', version='5.1.6')
println "Hello World!"
It looks like it should work, but it complains (here's the output the GroovyConsole Script):
startup failed:
Script1.groovy: 4: unexpected token: println # line 4, column 1.
println "hello"
^
1 error
Trying different things makes it work, like an import statement:
#Grab(group='mysql', module='mysql-connector-java', version='5.1.6')
import groovy.lang.Object
println "Hello World!" ​
Or a method declation:
#Grab(group='mysql', module='mysql-connector-java', version='5.1.6')
def hello() {}
println "Hello World!"
Is this a bug in the parser?
​
Grab can only be applied as an annotation to certain targets
#Target(value={CONSTRUCTOR,FIELD,LOCAL_VARIABLE,METHOD,PARAMETER,TYPE})
So you need to annotate one of those things (like you are seeing)
There is unfortunately no way in Java (and hence Groovy) of annotations just appearing in the middle of code.
test this
import static groovy.grape.Grape.grab
grab(group: "mysql", module: "mysql-connector-java", version: "5.1.6")
println "Hello World!"

Resources