Skip to content

Instantly share code, notes, and snippets.

@ismell
Created January 13, 2012 21:35
Show Gist options
  • Save ismell/1608819 to your computer and use it in GitHub Desktop.
Save ismell/1608819 to your computer and use it in GitHub Desktop.
RubyObject to SoyData
package com.test;
import org.jruby.RubyHash.Visitor;
import org.jruby.runtime.builtin.IRubyObject;
import org.jruby.RubyArray;
import org.jruby.RubyBignum;
import org.jruby.RubyBoolean;
import org.jruby.RubyFixnum;
import org.jruby.RubyFloat;
import org.jruby.RubyHash;
import org.jruby.RubyNil;
import org.jruby.RubyString;
import com.google.template.soy.data.*;
import com.google.template.soy.data.restricted.*;
public class SoyUtils {
public static SoyData ConvertRubyObjectToSoyData(IRubyObject object) {
SoyData data = null;
if (object == null || object instanceof RubyNil) {
data = NullData.INSTANCE;
} else if (object instanceof RubyHash) {
data = ConvertRubyHashToSoyData((RubyHash) object);
} else if (object instanceof RubyArray) {
data = ConvertRubyArrayToSoyData((RubyArray) object);
} else {
if (object instanceof RubyString) {
String string = ((RubyString) object).asJavaString();
data = new StringData(string);
} else if (object instanceof RubyBoolean) {
boolean bool = ((RubyBoolean) object).isTrue();
data = new BooleanData(bool);
} else if (object instanceof RubyFixnum) {
long num_value = ((RubyFixnum) object).getLongValue();
if (num_value >= Integer.MIN_VALUE || num_value <= Integer.MAX_VALUE) {
data = new IntegerData((int) num_value);
} else {
data = new FloatData(num_value);
}
} else if (object instanceof RubyBignum) {
double large = ((RubyBignum) object).getDoubleValue();
data = new FloatData(large);
} else if (object instanceof RubyFloat) {
double floating = ((RubyFloat) object).getValue();
data = new FloatData(floating);
} else {
Object unknown = object.toJava(Object.class);
data = SoyData.createFromExistingData(unknown);
}
}
return data;
}
public static SoyData ConvertRubyArrayToSoyData(RubyArray object) {
SoyListData list = new SoyListData();
for (long i = 0; i < object.getLength(); ++i) {
IRubyObject item = object.eltOk(i);
SoyData value = ConvertRubyObjectToSoyData(item);
list.add(value);
}
return list;
}
public static SoyData ConvertRubyHashToSoyData(RubyHash object) {
final SoyMapData root = new SoyMapData();
object.visitAll(new Visitor() {
public void visit(IRubyObject key, IRubyObject value) {
String key_str = null;
if (key instanceof RubyString) {
key_str = ((RubyString) key).asJavaString();
} else {
throw new IllegalArgumentException("Key must be a string");
}
SoyData value_soy = ConvertRubyObjectToSoyData(value);
root.put(key_str, value_soy);
}
});
return root;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment