When I pass a struct to a function that is expecting a struct, the function is nested inside another struct.
For example:
function getAnswerFromSO(struct question=StructNew()) {
writeDump(arguments.question);
}
CallinggetAnswerFromSO(question=myStruct); results in
question {
myStruct = {
text = 'foo',
subj = 'bar',
user = 1 }
};
** Obviously, this is not what a cfdump output looks like, but it illustrates the issue just the same.
Is there a way to prevent this nesting?
I can confirm that Ray's example works on CF9 as well.
Related
As I come from a JS background this is how I'd call a function by name stored in a variable:
var obj = {
foobar: function(param) {
// do something
}
};
var key = "foobar";
obj[key](123);
Now I would like to recreate this in Swift, for example:
struct obj = {
func foobar(param) {
// do something
}
}
let key:String = "foobar"
obj[key](123)
The above code unfortunately gives Type 'obj.Type' has no subscript members
Is there any way to call functions by names in a Struct, Class or a Dictionary (if it's even possible to store functions in Dicts?)
EDIT - MORE CONTEXT:
I have a user-supplied array of things say:
let arr = ["apples", "oranges", "pears"]
but this array can be as long as 20 items. Based on each item of the array I need to perform certain action. So I iterate over the array:
for (key, _) in arr {
if (key == "apples") {
handleApples()
}
if (key == "oranges") {
handleOranges()
}
// and so on...
}
Sure, I can have a function with a simple switch that would consist of 20 cases but that's far from ideal. What if my array grows to say 100 items?
I was hoping to achieve something similar to this:
for (key, _) in arr {
myClass[key]()
}
Is there any way to call functions by names in a Struct, Class or a Dictionary (if it's even possible to store functions in Dicts?)
Yes you can store a function into a dictionary
Let's define a function type
typealias FuncType = () -> ()
and 2 functions
func func0() {
print("Apples")
}
func func1() {
print("Oranges")
}
Now we can create a dictionary where the key is String and the value is FuncType
let dict : [String:FuncType] = [
"Apples" : func0,
"Oranges" : func1
]
And of course we can invoke a function stored into the dictionary
dict["Apples"]?() // prints "Apples"
I think this might be what you're looking for:
var obj: [String: Int] = {
// do something, like call foobar(param) that's defined outside of the variable
// or just manipulate data directly in here
return ["foobar": 123]
// or whatever dictionary you want that matches the type you defined for obj
}()
Kind of tough to give you a better answer without you posting the kind of output or behavior you're looking for.
The question is probably best asked with a simple example:
var myObj = { name: 'John' };
var copiedObj = ObjectCopier.copy(myObj);
copiedObj.name.should.equal('John'); // Hard code 'John' twice
copiedObj.name.should.equal(myObj.name); // Reference the original value
Is one method preferred over the other? Assuming the value passed in is what I expect to be returned, is there any harm in the 2nd assert? Does it even matter?
In more complex cases you won't be able to duplicate an object completely - and you wouldn't want to. it would be better written this way:
var OBJ_NAME = 'John'
var myObj = { name: OBJ_NAME };
var copiedObj = ObjectCopier.copy(myObj);
copiedObj.name.should.equal(OBJ_NAME);
this way you're not duplicating any code/defines, and you can also make tests such as:
myObj.name.should.equal(OBJ_NAME);
to test for the object copier not changing the original object either (which either of your lines won't test for).
I retrieve the selected typeahead value by using this method:
$('ul.typeahead li.active').data('value');
I then set this equal to a variable, like so,
var foo = $('ul.typeahead li.active').data('value');
However, if I try and do something like this:
var foo = $('ul.typeahead li.active').data('value').replace( /\([^\)]+\)$/, '' );
it won't seem to update the value of foo even though when I console.log(foo) it actually is showing the right value for foo.
Can you please tell me what I could do to resolve this?
Data returns an object and not a String
Try :
var foo = $('ul.typeahead li.active').data('value').first.replace( /\([^\)]+\)$/, '' );
Here's basically what I want to accomplish:
{exp:plugin1:method arg="{exp:plugin2:method}"}
I’ve tried a number of different approaches.
Approach 1:
{exp:plugin1:method arg="{exp:plugin2:method}"}
Result: Plugin1->method’s arg parameter value is the string, {exp:plugin2:method}, and it’s never parsed.
Approach 2:
My understanding of the parsing order suggests that this might have different results, but apparently it does not.
{preload_replace:replaced="{exp:plugin2:method}"}
{exp:plugin1:method arg="{replaced}"}
Result: The arg parameter has the same value as approach 1.
Approach 3:
First I define a snippet (snip), whose content is:
{exp:plugin2:method}
Then in the template:
{exp:plugin1:method arg="{snip}"}
Result: Same as approaches 1 and 2.
Approach 4:
Noting that plugins are processed in the order they appear, I have even tested simply placing an instance of {exp:plugin2:method} before the {exp:plugin1:method} call. My thinking is that I could wrap this first call in a regex replacement plugin in order to suppress output, but that it would trigger Plugin2’s parsing first.
{exp:plugin2:method}
{exp:plugin1:method arg="{exp:plugin2:method}"}
Result: Plugin1->method’s arg parameter value is the temporary hash placeholder for Plugin2->method’s output (MD5 I believe) that the Template class reserves until later.
Interesting approach. However, this can be achieved more simply like this:
{exp:plugin1:method arg="{exp:plugin2:method}" parse="inward"}
I have a workaround, but I'll wait a while to see if a better solution comes up before I accept my own answer. The workaround is to wrap plugin1 with plugin2 and replace template tags referring to its methods within the tagdata. Note that this requires a parse="inward" parameter on the plugin2 call.
In the template:
{exp:plugin2 parse="inward"}
{exp:plugin1:method arg="{someplugin2method}"}
{/exp:plugin2}
In the plugin class:
static $public_methods;
function __construct() {
// Actual construction code omitted...
if(($tagdata = $this->EE->TMPL->tagdata) !== false && trim($tagdata) !== '') {
if(!isset(self::$public_methods)) {
self::$public_methods = array();
$methods = get_class_methods($this);
foreach($methods as $method) {
if($method == get_class($this) || $method == '__construct') {
continue;
}
$reflection = new ReflectionMethod(get_class($this), $method);
if($reflection->isPublic()) {
self::$public_methods[] = $method;
}
}
self::$public_methods = implode('|', self::$public_methods);
}
$tagdata = preg_replace_callback('/\{(' . self::$public_methods . ')\}/',
array($this, 'tagdata_callback'), $tagdata);
$this->return_data = $tagdata;
}
}
private function tagdata_callback($matches) {
$method = $matches[1];
return $this->$method();
}
Caveats:
This can make for messier templates.
Maintaining a list of public methods apparently requires Reflection which is not available in PHP 4. You can, of course, maintain a list of expected methods manually.
I've got a class that's meant to validate input fields to make sure the value is always a decimal. I've tested the regex here: http://livedocs.adobe.com/flex/3/html/help.html?content=validators_7.html, and it looks like it does the right thing, but in my app, I can't seem to get it to match to a number format.
Class Definition:
public class DecimalValidator {
//------------------------------- ATTRIBUTES
public var isDecimalValidator:RegExpValidator;
//------------------------------- CONSTRUCTORS
public function DecimalValidator() {
isDecimalValidator = new RegExpValidator();
isDecimalValidator.expression = "^-?(\d+\.\d*|\.\d+)$";
isDecimalValidator.flags = "g";
isDecimalValidator.required = true;
isDecimalValidator.property = "text";
isDecimalValidator.triggerEvent = FocusEvent.FOCUS_OUT;
isDecimalValidator.noMatchError = "Float Expected";
}
}
Setting the source here:
public function registerDecimalInputValidator(inputBox:TextInput, valArr:Array):void {
// Add Validators
var dValidator:DecimalValidator = new DecimalValidator();
dValidator.isDecimalValidator.source = inputBox;
dValidator.isDecimalValidator.trigger = inputBox;
inputBox.restrict = "[0-9].\\.\\-";
inputBox.maxChars = 10;
valArr.push(dValidator.isDecimalValidator);
}
And Calling it here:
registerDecimalInputValidator(textInput, validatorArr);
Where textInput is an input box created earlier.
Clearly I'm missing something simple yet important, but I'm not entirely sure what! Any help would be much appreciated.
I don't know ActionScript, but as far as I know it's an ECMAScript language, so I expect you need to escape the backslashes if you use a string to define a regex:
isDecimalValidator.expression = "^-?(\\d+\\.\\d*|\\.\\d+)$";
This strikes me as wrong; but I can't quite put my finger on it. For your DecimalValidator instead of composing a RegExpValidator; why not extend it?
public class DecimalValidator extend RegExpValidator{
//------------------------------- CONSTRUCTORS
public function DecimalValidator() {
super()
this.expression = "^-?(\d+\.\d*|\.\d+)$";
this.flags = "g";
this.required = true;
this.property = "text";
this.triggerEvent = FocusEvent.FOCUS_OUT;
this.noMatchError = "Float Expected";
}
}
How when is the registerdecimalInputValidator called? I have a slight worry about the Validator instance is a local variable to a method instead of 'global' property to the function.
protected var dValidator:DecimalValidator = new DecimalValidator();
public function registerDecimalInputValidator(inputBox:TextInput):void {
dValidator.isDecimalValidator.source = inputBox;
dValidator.isDecimalValidator.trigger = inputBox;
}
I'm not sure why you are setting restrictions on the TextInput in the registerDecimalInputValidator method; that should be done when you create the method (in createChildren() or possibly in response to public properties changing, in commitProperties . It is also not obvious to me what the validatorArr does. If you're expecting to access values inside the validatorArrray outside of the method; it would often be a common practice to return that value from the method. Without looking it up; I'm not sure if Arrays are passed by value or reference in Flex.