Hi, I was trying out ways to create a micro-DSL using JRuby.
*A) *I wanted to do instance_eval on a Java class. On my first attempt
I
got this warning message: “warning: singleton on non-persistent Java
type
Java::JrDemo::Car (http://wiki.jruby.org/Persistence)”
require ‘java’
def configure(&block)
car = Java::jr.demo.Car.new
car.instance_eval &block
car
end
@car = configure do |car|
car.model = ‘S2000’
car.make = ‘Honda’
car.year = 2002
car.price = 19000
end
return @car
Car is a simple Java Bean:
public class Car {
String model;
String make;
int year;
double price;
public Car() {
}
public String getModel() {
return model;
}
public void setModel(String model) {
this.model = model;
}
… … more getters and setters
}
*B) After reading the instructions on that Persistence page, I tried
sub-classing the Java class inside JRuby. I also wanted to do the *
instance_eval inside the initialize method. When I ran the code, it
barfed with this exception - “Java wrapper with no contents:
#Class:0x5584d9c6”
require ‘java’
class JCar < Java::jr.demo.Car
def initialize(&block)
instance_eval &block
end
end
@car = JCar.new do |car|
car.model = ‘S2000’
car.make = ‘Honda’
car.year = 2002
car.price = 19000
end
return @car
*C) *To make sure that I wasn’t doing something stupid, I did the
instance_eval in a non-initialize method and it worked:
require ‘java’
class JCar2 < Java::jr.demo.Car
def configure(&block)
instance_eval &block
end
end
@car2 = JCar2.new
@car2.configure do |car|
car.model = ‘S2000’
car.make = ‘Honda’
car.year = 2002
car.price = 19000
end
return @car2
*D) *Just to be sure if it was a JRuby peculiarity or a Ruby thing, I
tried
a pure Ruby class and everything worked!
class RCar
attr_accessor :model, :make, :year, :price
def initialize(&block)
instance_eval &block
end
def to_s
"{#{self.class.name}: #{@model}, #{@make}, #{@year}, #{@price}}"
end
end
@rcar = RCar.new do |car|
car.model = ‘S2000’
car.make = ‘Honda’
car.year = 2002
car.price = 19000
end
return @rcar
What do you guys think? Am I doing something wrong or is the JRuby doc
missing this information?
Thanks,
Ashwin Jayaprakash (http://ashwinjayaprakash.com)