@ Machado'nun dediği gibi, bunu yapmanın en kolay yolu onu önlemek ve tüm işlemlerinizi ana java'da yapmaktır. Bununla birlikte, her iki kod tabanı için bir kod oluşturarak kendi kodunuzu kendiniz tekrarlamadan, benzer kodla temel vermek zorunda kalırsınız.
Örneğin , ortak bir tanımdan üç parçacığı oluşturmak için cog enable özelliğini kullanma
snippet 1:
/*[[[cog
from generate import generate_sql_table
cog.outl(generate_sql_table("rectangle"))
]]]*/
CREATE TABLE rectangles (
width int,
height int
);
/*[[[end]]]*/
pasaj 2:
public class Rectangle {
/*[[[cog
from generate import generate_domain_attributes,generate_domain_logic
cog.outl(generate_domain_attributes("rectangle"))
cog.outl(generate_domain_logic("rectangle"))
]]]*/
private int width;
private int height;
public int area {
return width * heigh;
}
/*[[[end]]]*/
}
snippet 3:
/*[[[cog
from generate import generate_sql
cog.outl(generate_sql("rectangle","""
SELECT sum({area})
FROM rectangles r"""))
]]]*/
SELECT sum((r.width * r.heigh))
FROM rectangles r
/*[[[end]]]*/
bir referans dosyasından
import textwrap
import pprint
# the common definition
types = {"rectangle":
{"sql_table_name": "rectangles",
"sql_alias": "r",
"attributes": [
["width", "int"],
["height", "int"],
],
"methods": [
["area","int","this.width * this.heigh"],
]
}
}
# the utilities functions
def generate_sql_table(name):
type = types[name]
attributes =",\n ".join("{attr_name} {attr_type}".format(
attr_name=attr_name,
attr_type=attr_type)
for (attr_name,attr_type)
in type["attributes"])
return """
CREATE TABLE {table_name} (
{attributes}
);""".format(
table_name=type["sql_table_name"],
attributes = attributes
).lstrip("\n")
def generate_method(method_def):
name,type,value =method_def
value = value.replace("this.","")
return textwrap.dedent("""
public %(type)s %(name)s {
return %(value)s;
}""".lstrip("\n"))% {"name":name,"type":type,"value":value}
def generate_sql_method(type,method_def):
name,_,value =method_def
value = value.replace("this.",type["sql_alias"]+".")
return name,"""(%(value)s)"""% {"value":value}
def generate_domain_logic(name):
type = types[name]
attributes ="\n".join(generate_method(method_def)
for method_def
in type["methods"])
return attributes
def generate_domain_attributes(name):
type = types[name]
attributes ="\n".join("private {attr_type} {attr_name};".format(
attr_name=attr_name,
attr_type=attr_type)
for (attr_name,attr_type)
in type["attributes"])
return attributes
def generate_sql(name,sql):
type = types[name]
fields ={name:value
for name,value in
(generate_sql_method(type,method_def)
for method_def in type["methods"])}
sql=textwrap.dedent(sql.lstrip("\n"))
print (sql)
return sql.format(**fields)