I am learning how to integrate Java library with Ruby code and come to the following question.
I have a command pattern implemented in Java, as follows:
public interface Command {
public String execute(String param);
}
public class CommandRunner {
public String run(Command cmd, String param) {
return cmd.execute(param)+" [this is added by run method]";
}
}
When I import that to JRuby program I can implement Ruby class that respond_to? :execute with one parameter and pass it to the CommandRunner.new.run. That works and that's clear.
But I can also do this:
def put_through_runner(param, &block)
CommandRunner.new.run block, param
end
p = put_through_runner "through method" do |param|
"Cmd implementation in block, param: #{param}"
end
puts p
Instead of passing to Java CommandRunner an object implementing the execute method I pass it a block of code, that does not implement the method. And It works: calls the block as if it was implementation of the execute method! How is that possible? What does JRuby do with the block when passing it to Java? If I had the CommandRunner implemented in Ruby the above code would not work.
executemethod to your proc object. you could check that in yourput_through_runnermethod.executemethod. First: there is nothing that could do it, second: that was the first thing I checked -- in theput_through_runnermethod theblockobject does notrespond_to? :execute.respond_to?returningfalsedoes not necessary mean that this is actually the case. it depends on the wayrespond_to?is implemented.