Ruby inside .NET and Java
Posted on January 27th, 2009 in Programming, Ruby | No Comments »
In the past I have played around with JRuby and accessing some of the Java framework from Ruby. Its fantastic and I have raved about it infront of my friends in the past. Microsoft as well now have a product called IronRuby which runs Ruby inside Microsofts Dynamic Language Runtime (DLR). IronRuby is a Ruby interpereter which runs in the DLR and as a byproduct gives Ruby access to the .NET framework (yay, power to the programmer!).
I just thought I would blog about this little code snippet I put together on the weekend for some fun. It retrives the IP addresses for the interfaces on the machine it is run on. If it is run in JRuby (inside the JVM) it uses the Java framework to retrieve the interfaces and print them. If it is running in IronRuby (inside the DLR) it uses the .NET framework to retreive the IP addresses. Finally, if it is not running in either of those it reports that we are not running in either the JVM or the DLR and exits.
I suspect this may be a handy thing to do if you have common tasks which you perform accross the two different environments (Java and .NET) as you dont have to expose functionality from inside your environment, you can intergrate directly into it using the same language (with a bit of added abstraction on your part)
I just thought I would blog about this little code snippet I put together on the weekend for some fun. It retrives the IP addresses for the interfaces on the machine it is run on. If it is run in JRuby (inside the JVM) it uses the Java framework to retrieve the interfaces and print them. If it is running in IronRuby (inside the DLR) it uses the .NET framework to retreive the IP addresses. Finally, if it is not running in either of those it reports that we are not running in either the JVM or the DLR and exits.
I suspect this may be a handy thing to do if you have common tasks which you perform accross the two different environments (Java and .NET) as you dont have to expose functionality from inside your environment, you can intergrate directly into it using the same language (with a bit of added abstraction on your part)
path = {
otNet => lambda {
require 'System.Management, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'
mc = System::Management::ManagementClass.new("Win32_NetworkAdapterConfiguration")
moc = mc.GetInstances()
moc.each { |v| p v.GetPropertyValue("ipAddress") if v.GetPropertyValue("ipEnabled") }
},
:Java => lambda {
java.net.NetworkInterface.networkInterfaces.each { |v| puts v }
},
:None => lambda {
puts "Sorry, you are not running in the JVM or DLR"
}
}
begin
# If we are in IronRuby we have access to the .NET classes
require 'mscorlib'
call =
otNet
rescue Exception => e
begin
include Java
call = :Java
rescue Exception => e
call = :None
end
end
path[call].call()