From ce9a034f89eb28bfa71d1db0a1526e168dd14c2b Mon Sep 17 00:00:00 2001
From: Mauricio Giacomini Girardello <mauriciogiacomini4@gmail.com>
Date: Tue, 3 Nov 2015 11:33:54 -0200
Subject: [PATCH] create builder for collection models

---
 app/builders/collection_builder.rb            | 40 +++++++++++++++++++
 .../orient_db/collection_repository.rb        | 13 +-----
 2 files changed, 41 insertions(+), 12 deletions(-)
 create mode 100644 app/builders/collection_builder.rb

diff --git a/app/builders/collection_builder.rb b/app/builders/collection_builder.rb
new file mode 100644
index 00000000..e096cf68
--- /dev/null
+++ b/app/builders/collection_builder.rb
@@ -0,0 +1,40 @@
+class CollectionBuilder
+  extend RepositoriesProxy
+
+  ##
+  # receive a list of ids and return a list of collections
+  def self.build(objects = [])
+    lo = []
+    objects.each do |object|
+      unless object['rid'].blank?
+        o = Rails.cache.fetch(cache_key(object['rid'], object['last_modified']))
+        o = collection_repository.find object['rid'] if o.nil?
+        lo << o
+      end
+    end
+    lo
+  end
+
+  def self.build_from_orientdb(args = {})
+    lo = nil
+    unless args.nil?
+      # cache object when build
+      lo = Rails.cache.fetch(cache_key(args['@rid'], args['last_modified']), expires_in: 12.hours) do
+        obj = Collection.new(
+            learning_objects: LearningObjectBuilder.build(args['learning_objects'] || []),
+            privacy: args['privacy'],
+            name: args['name'],
+            id: args['@rid']
+        )
+        obj.created_at = DateTime.strptime(args['created_at'], "%Y-%m-%d %H:%M:%S") unless args['created_at'].nil?
+        obj.last_modified = DateTime.strptime(args['last_modified'], "%Y-%m-%d %H:%M:%S") unless args['last_modified'].nil?
+        obj
+      end
+    end
+    lo
+  end
+
+  def self.cache_key(rid, last_modified)
+    rid + '/' + last_modified
+  end
+end
diff --git a/app/repositories/orient_db/collection_repository.rb b/app/repositories/orient_db/collection_repository.rb
index 9a2eb5a9..c64c4a70 100644
--- a/app/repositories/orient_db/collection_repository.rb
+++ b/app/repositories/orient_db/collection_repository.rb
@@ -4,7 +4,7 @@ module OrientDb
     include OrientDb::Methods::FinderMethods
 
     def build_object(args={})
-      Collection.new(map_object_hash(args))
+      CollectionBuilder.build_from_orientdb args
     end
 
     def save(collection = Collection.new)
@@ -85,17 +85,6 @@ module OrientDb
 
     private
 
-    def map_object_hash(hash={})
-      {
-          created_at: hash['created_at'],
-          last_modified: hash['last_modified'],
-          learning_objects: hash['created_at'],
-          privacy: hash['privacy'],
-          name: hash['name'],
-          id: hash['@rid']
-      }
-    end
-
     def odb_class
       'Collection'
     end
-- 
GitLab