Assigning actions to a variable

2019-08-04 04:58发布

问题:

In answering Aaron's recent question, I'd like to do something like the following:

rule first_rule {
    select when pageview "exampley.com/\?name=(.*)" setting (username)
    pre {
        isjoe = username eq "joe";
        myaction = defaction() {
            thisaction = isjoe => notify("Hello, World", "Hi there, Joe!") | noop();
            thisaction();
        };
    }
    {
        notify("Will it work?", "Methinks you are #{username}");
        myaction();
    }
}

However, the defaction never seems to work. It doesn't like that I'm trying to assign an action to a variable and then return that variable.

What am I doing wrong?

回答1:

You are really close.

You can't call an action till the end of the defaction. You need to create a defaction that delays execution till the right time.

Change:

thisaction = isjoe => notify("Hello, World", "Hi there, Joe!") | noop();

to

thisaction = isjoe => defaction(){notify("Hello, World", "Hi there, Joe!");} | noop;

Note the added defaction and I removed the parens from noop.

This concept is is similar to javascript closures.



标签: krl