在ColdFusion中将字符串转换为闭包

时间:2014-05-26 17:03:50

标签: coldfusion closures railo

我有一个非常基本的问题。是否可以将字符串转换为闭包?我试过评价(),但它没有用。

evaluate( "myFunction = function(val){ return dollarFormat( val ); }" );

我的想法是将自定义函数作为字符串保存在数据库中,然后根据需要运行它。

谢谢!

编辑:只是为了澄清:我希望能够保存"功能(val){return dollarFormat(val); }"作为数据库中的字符串,并能够将其转换为功能闭包。

2 个答案:

答案 0 :(得分:0)

我会选择user2943775回答:

<cfscript>
FileWrite("/ram/UDFs.cfm", "<cfset myFunction = function(val){ return dollarFormat( val ); }>")
include template="/ram/UDFs.cfm";
writedump(myFunction(10));
</cfscript>

在你的Application.cfc

component {
    this.mappings["/ram"] = "ram://";
    ...
}

答案 1 :(得分:0)

我遇到了类似的解决方案,但由于安全限制,我无法使用内存中的文件系统。在我的Application.cfc中,我添加了以下映射:

this.mappings = {
    "/models" = "#APP_ROOT_PATH#cfcs/models",
    "/utils" = "#APP_ROOT_PATH#cfcs/utils",
    "/modules" = "#APP_ROOT_PATH#_modules",
    "/components" = "#APP_ROOT_PATH#cfcs",
    "/udfs" = "#APP_ROOT_PATH#includes/udfs" // path for global (and temporary) UDFs
};

我创建的UDF如下:

/**
 * Takes a string representation of a function and returns it as a Closure
 * @output false
 * @return Closure
 */
private any function toClosure (required string closure) {
    local.id = replace(createUUID(), "-", "", "all");
    local.udfpath = "/udfs/udf#id#.cfm";
    local.script = "<cfscript>local.fn#id# = #closure#;</cfscript>";

    try {
        fileWrite(expandPath(udfPath), script);
        include udfpath;
    } catch (any e) {

    } finally {
        try {
            fileDelete(expandPath(udfPath));
        } catch (any e) {}
    }

    if (!structkeyExists(local, "fn#id#") || !isClosure(local["fn#id#"])) {
        throw (message="Unable to compile closure");    
    }

    // return the closure
    return local["fn#id#"];         
}

结果:

myFn = toClosure("function (num) { return num + 1; }");
myFn(1); // returns 2