I’m coding up some delicious business logic and I’ve come to a situation like this:
There are a bunch of rules (ruleA, ruleB, etc…) which all follow a standard pattern. I’ve created a Rule interface, and implemented it in RuleA, RuleB, and so on.
So now I just need a way to load them.
Right now I’m using a map:
var rules:Object = {
ruleA: new RuleA(),
ruleB: new RuleB(),
...
};
Then calling it like this:
function doStuff(whichRule:String, someData:Object):* {
return rules[whichRule].applyTo(someData);
}
Now, the rules follow a standard naming scheme, and they are all part of one package (foo.rules)… Is there any way to load the rules without keeping them some sort of list?
Thanks!
Edit: To clarify, would like to discover the possible rules at runtime so I don’t need to maintain a list of rules. For example:
function loadRule(name:String):Rule {
import foo.rules;
var rule:Class = foo.rules[name];
return new rule();
}
Except, of course, I can’t index into the foo.rules namespace… But that’s what I’d like to be able to do.
You can get a reference to a class from a string with the flash.utils.getDefinitionByName(className);
For example
In the example above you are returning a class, but you can also instantiate it and return the object.
Note however that this will only work if the class, identified by the class name is compiled into your swf. If no where else in your code you refer to that class, or else it won’t be compiled. This is usually achieved creating references in some other piece of code or your build system can pass that to the compiler.
Do note, that functions are first class objects in AS3, so, depending on your use case, you can define each rule as a function to a Rule class and pass that:
That depends on how much logic you’d like to put into those, and how much common code there is between those rules, of course.