From: David Lutterkort <[email protected]>
We reuse the CIMI::Model::Collection class that is also used for toplevel
collections. With that, we won't need special purpose XXXCollection
classes.
---
server/lib/cimi/models/base.rb | 3 ++
server/lib/cimi/models/schema.rb | 45 +++++++++++++++++++++++++++++++++----
2 files changed, 43 insertions(+), 5 deletions(-)
diff --git a/server/lib/cimi/models/base.rb b/server/lib/cimi/models/base.rb
index 2a27a8f..2e66694 100644
--- a/server/lib/cimi/models/base.rb
+++ b/server/lib/cimi/models/base.rb
@@ -66,6 +66,9 @@ require 'json'
# [array(name, opts, &block)]
# An array of structured subobjects; the block defines the schema of
# the subobjects.
+# [collection(name, opts)]
+# A collection of associated objects; use the +:class+ option to
+# specify the type of the collection entries
module CIMI::Model
diff --git a/server/lib/cimi/models/schema.rb b/server/lib/cimi/models/schema.rb
index e679b2e..d8ba13b 100644
--- a/server/lib/cimi/models/schema.rb
+++ b/server/lib/cimi/models/schema.rb
@@ -216,6 +216,41 @@ class CIMI::Model::Schema
end
end
+ class Collection < Attribute
+ def initialize(name, opts = {})
+ super(name, opts)
+ unless opts[:class]
+ raise "Specify the class of collection entries using :class"
+ end
+ @collection_class = CIMI::Model::Collection.generate(opts[:class])
+ end
+
+ def from_xml(xml, model)
+ raise "Parsing collections (#{name}) not supported"
+ end
+
+ def from_json(json, model)
+ raise "Parsing collections (#{name}) not supported"
+ end
+
+ def to_xml(model, xml)
+ xml[xml_name] = @collection_class.schema.to_xml(model[name])
+ end
+
+ def to_json(model, json)
+ json[json_name] = @collection_class.schema.to_json(model[name])
+ end
+
+ # Convert a Hash or Array to an instance of the collection class
+ def convert(value)
+ if value.is_a?(::Array)
+ @collection_class.new(:entries => value)
+ else
+ @collection_class.new(value || {})
+ end
+ end
+ end
+
#
# The actual Schema class
#
@@ -226,6 +261,10 @@ class CIMI::Model::Schema
@attributes = []
end
+ def collections
+ @attributes.select { |a| a.is_a?(Collection) }
+ end
+
def convert(name, value)
attr = @attributes.find { |a| a.name == name }
raise "Unknown attribute #{name}" unless attr
@@ -303,11 +342,7 @@ class CIMI::Model::Schema
end
def collection(name, opts={})
- text :count
-
- array :operations do
- scalar :rel, :href
- end
+ add_attributes!([name, opts], Collection)
end
end
--
1.7.7.6