jetrockets/attrio — pull request #5 by anithri (2013-06-25 21:48:25+00:00)
Title: This is a sampling of code meant to demonstrate collections for attrio.

This request is meant for discussion, it is unready for merging.

I'm going to do this work, but I wanted to know what you guys thought of it. It could also be implemented as a plugin for Attrio.

I love the Attrio code so far, and I'm planning to use it in another project soon. However, I need to have similar functionality for collections of objects in addition to the attributes already provided. This outlines one way to accomplish this.

We start by modifying AttributesParser to include a #collection public method which allow you to define collections. Each collection has 3 groups of methods. a Reader which gives you full access to the collection. a AddElement, which adds a new element to the array, and a FindElement which will allow you to read a single element of the collection based on an index.

Collections may be 1 of 3 types. With no special options, Attrio::Collection will create an Array. With a :unique options key set to true and no :index key, Attrio::Collection will create a Set. With a :unique key set to true and an :index key, Attrio::Collection will create a hash, and will call the method defined by the :index key and use the result as the hash key. This would allow you to do something like...

```ruby
class ClassSection
include Attrio
define_attributes do
attr :name, String
attr :teacher, Faculty
collection :students, Student, unique: true, index: :student_id
collection schedule, DateTime, unique: true
collection reading_materials, String
end
end
```

the students collection would be a hash in this case, using the return value from student.student_id, as the key.
The schedule collection would be a set, and the reading_materials collection would be an array.

FindElement can be used for any container, the default value defined for the collection will be returned if no element is found.

AddElement should be structured to accept an array of hashes that can be used to add a number of elements at the same time as well as adding only a single one at a time.

This code is not tested yet.

Readme changes are examples of using Collections.
attributes_parser had collection, create_collections, and
fetch_container_type methods added.
collection is a class parallel to Attribute for use with collections.