Iterating Over Array Literal - dust.js

Is it possible in dust to iterate over an array literal?
If I had JSON with like so {arr: ["a", "b", "c"]} I would do:
{#arr}
....
{/arr}
Is there a way to do this with an array I define in the dust template? Perhaps something like:
{#["a", "b", "c"]}
{/?}
I know that's not correct syntax, but hopefully it illustrates what I'm trying to do.

Dust doesn't include this language functionality natively. That's why you can write helpers in your context or as global functions to add new features to Dust.
Here's a basic helper that iterates over a list of items. There's no error checking or anything, but it's a starting point.
dust.helpers.iterate = function(chunk, context, bodies, params) {
var items = params.items.split(',');
return chunk.section(items, context, bodies, params);
}
Then, use it in your template:
{#iterate items="ab,cd,ef,12"}
Item: {.}{~n}
{/iterate}
If you are using this in a single context, you can place helpers directly into your Dust context as well, and invoke them like {#iterate}.

Related

How to create a "constant reference" getter in Dart?

Say I have a class ListContainer that contains and manages a list that must be accessible from outside. Since managing this list is complicated, I don't want to let anyone other than ListContainer modify it. In C++, I would create a function that returns const reference, but in Dart, const works completely differently. Just using getter will not prevent someone from modifying the list.
So how can I provide an access to the list values without allowing to modify the list?
I'm looking for something better than creating a getNth function because that would also require creating methods like length, map, and so on.
I think UnmodifiableListView is what you are looking for.
check out UnmodifiableListView Documentation
you can use it like this:
List<int> _myList = [1, 2, 3];
UnmodifiableListView<int> get myList => UnmodifiableListView(_myList);

How do you define custom objects in-line in actionscript?

I'd like to define a psuedo strongly typed object but still be able to define it inline.
current solution:
callMethod({param1:paramvalue,param2:paramvalue2});
I'd like to use similar inline syntax but the parameter 'object' to only contain a specific list of parameters. IE: only allow param1 & param2 but not param3.
I'd be happy with something like this:
callMethod(mytype(param1:paramvalue,param2:paramvalue2);
This is what you want:
callMethod( new MyType(paramvalue, paramvalue2) );

Ruby Integer(), Array(), et al -- what are they? Where do they come from?

I've come across conversions of the form Array(value), String(value), and Integer(value) on occasion. It appears to me that these are just syntactic sugar for a call to the corresponding value.to_a, value.to_s, or value.to_i methods.
So I'm wondering:
Where/how are these are defined? I can't find them in Object, Module, Class, etc
Are there any common scenarios for which it's preferable to use these rather than the corresponding/underlying to_X method?
Could these be used in type-generic coercion? That is, can I do something along the lines of
[Integer, String, Array].each {|klass| klass.do_generic_coercion(foo) }
? (...and no, I don't really want to do that; I know the type I want out, but I'm looking to avoid the case statement.)
This is a good and difficult question. Let's answer the three parts.
First part
To find the definition, it is important to realize that the name of the method is "Array", etc., which can be quite counterintuitive, since methods are usually lowercase...
irb> method(:Array)
=> #<Method: Object(Kernel)#Array>
This tells you these are defined in Kernel, and thus available everywhere without requiring an explicit prefix.
Second part
Array(), String(),... are conversion methods. Calling obj.to_a will return an array, but will raise an NoMethodError if obj doesn't respond_to? :to_a. So the typical case when you'd prefer using Array(), String(), instead of to_a or to_s is when you are not positive an object responds to a given conversion method.
String(obj) will return nil if obj doesn't respond_to? :to_s. String(obj) will also check that the result of to_s is actually a string; it should be, but maybe an overly creative programmer decided to return something else?
Most other conversion methods act the same way, but Array(obj) is different. It will return [obj] if obj doesn't respond_to? :to_a. It will actually call to_ary (which is the implicit conversion operation, while to_a is the explicit one).
There is another important way to convert objects in 1.9 (and upcoming 1.8.8): Array.try_convert(obj). This returns nil if the obj does not respond_to? :to_ary. It will not call the to_a. Although they are longer to type, you might prefer using them when writing very general code that might accept different types of objects and want to avoid converting a hash to an array by mistake, for example (since Hash has a to_a method but not to_ary). When your method requires an array-like object and you are willing to do an explicit conversion, then obj.to_a is fine. The typical use of Array(obj) would be in a method that accepts either a single obj to act on, or a list of objects (although typically this is written as [*obj]).
Last part
Hopefully, the answers to the first two parts give you your final answer...
You can use:
[Integer, String, Array].each {|klass| klass.try_convert(foo) }
or
[:Integer, :String, :Array].each{|method| send(method, obj)}
Good question! Let's see if we can figure it out.
Ross-Harveys-MacBook-Pro:ruby-1.9.1-p376 ross$ irb
irb(main):001:0> Object.ancestors
=> [Object, Kernel]
irb(main):002:0> Kernel.ancestors
=> [Kernel]
irb(main):003:0> Kernel.class
=> Module
irb(main):004:0> Kernel.public_methods.include? "Array"
=> true
So, it looks like these are methods in the Kernel module that are mixed in to Object, so they are available without specifying a receiver. We might also want to peek at the C implementation, in object.c:
VALUE
rb_Array(VALUE val)
{
VALUE tmp = rb_check_array_type(val);
if (NIL_P(tmp)) {
tmp = rb_check_convert_type(val, T_ARRAY, "Array", "to_a");
if (NIL_P(tmp)) {
return rb_ary_new3(1, val);
}
}
return tmp;
}
One thing seems easy to conclude, the default .to_a is deprecated, so it does seem like Array(x) is the canonical way to do the conversion. It apparently does nothing if given an Array, calls .to_a if that's present, and if not it just wraps its argument in an Array.
Regarding whether to_a is deprecated...well, I said "the default":
Ross-Harveys-MacBook-Pro:puppet_sd ross$ irb
irb(main):001:0> class X; X; end.new.to_a
(irb):1: warning: default `to_a' will be obsolete
They are Defined in Ruby Kernel Module, like:
Array(), Complex(), Float(), Integer(), Rational(), Stirng(), etc.
I found those method references in Dave Thomas's Pickaxe book "Progamming Ruby 1.9", page 555.
For example: Array(arg) will convert arg as an Array, following are copied from the book:
"Returns arg as an Array. First tries to call rg.to_ary, then arg.to_a. If both fail, creates a single element array containing arg( or an empty array if arg is nil)."
ex. Array(1..5) # => [1, 2, 3, 4, 5]
From what I understand, the simple version is like this:
object.to_a tries to convert 'object' to an Array using a class member function.
Array(object) tries to make a new Array using 'object'.
I can re-define what .to_a means for a given class (it is just another member after all). The Array(...) call is defined in Kernel so it behaves the same for any class. I typically use type conversions of the style Array(...) when I don't know ahead of time what type of object will be passed in. It's better at handling cases where an object doesn't know how to convert itself to an array or can't be converted to an array. If the object to be converted is the result of a long or complex expression, using the Array(...) style is often clearer. I save the .to_a form for instances when I know the class of the object and exactly what to expect from the output of .to_a (mostly instances when I have written or modified the .to_a member function myself).

Using bindData method outside of controller

I was wondering if anyone had an idea for the best way to provide the
functionality of bindData() outside of my grails controllers. In my current
project I have created several groovy classes to model objects returned by
an api. In these classes I have a static method that parses xml and returns
a List of objects of the class. I would like to skip all the type casting
nonsense by using the bindData method in these classes. Any suggestions on
how to do this would be appreciated.
I was looking for a similar solution, to use bindData in a service class. I found a solution in JT's blog. The solution is basically to import:
import org.codehaus.groovy.grails.web.metaclass.BindDynamicMethod
then add this to your code:
def foo = new Foo()
BindDynamicMethod bind = new BindDynamicMethod()
def args = [ foo, params, [exclude:['name', 'mail']] ] // for example
bind.invoke( foo, 'bind', (Object[])args)
The (Object[]) cast is necessary du to Groovy/Java compatability. (Groovy is treating the ‘args’ object as an ArrayList, not an array of Objects.)

Groovy object array creation question

why does this throw an exception?
messageSource.getMessage('UserService.msg.forgot.unknown', ["test#mail.com"], null)
unless I do this...
def Object[] args = ["test#mail.com"]
messageSource.getMessage('UserService.msg.forgot.unknown', args, null)
Because ["test#mail.com"] evaluates to an ArrayList, not an array:
groovy:000> o = ["asdf"]
===> [asdf]
groovy:000> o.getClass()
===> class java.util.ArrayList
OTOH your declaration creates an array of Objects:
groovy:000> Object[] args = ["asdf"]
===> [Ljava.lang.Object;#14e113b
and the method you're calling needs an array. You can create an array using as:
Object[] args = ["asdf"] as Object[]
The Groovy creators made a point of making higher-level data structures like lists idiomatic, while arrays are present for interoperability with Java.
In his interview in Coders at Work Guy Steele talks about choices made in designing a language:
"There's this Huffman encoding problem. If you make something concise,
something is going to have to be more verbose as a consequence. So in
designing a language, one of the things you think about is, 'What are
the things I want to make very easy to say and very easy to get
right?' But with the understanding that, having used up characters or
symbols for that purpose, you're going to have to make something else
a little bit harder to say."
It certainly looks like Groovy made lists more concise, with the side effect that arrays became more verbose.
Nathan has already (correctly) explained the reason for this behavior at the language level. I just want to move one abstraction level up: Why are you using Spring's MessageSource directly, in the first place? In Grails there is a message tag, that wraps the message source:
g.message(code: 'UserService.msg.forgot.unknown', args: ["test#mail.com"])

Resources