Commit 576a0458

mo <mo.khan@gmail.com>
2017-09-24 22:41:58
bind auto collections to a url.
1 parent 79f4216
Changed files (4)
app
spec
app/assets/javascripts/models/auto_collection.js.coffee
@@ -1,6 +1,10 @@
 class csx.AutoCollection
-  @install: (collectionName, json) ->
-    csx.Collections[collectionName] = @create(json)
-
-  @create: (json) ->
-    new Backbone.Collection(json)
+  @install: (modelName, pluralName, json) ->
+    model = csx.Models[modelName]
+    if _.isUndefined(model)
+      csx.Collections[modelName] = new Backbone.Collection(json)
+    else
+      collection = Backbone.Collection.extend
+        model: model
+        url: "/api/v1/#{pluralName}"
+      csx.Collections[modelName] = new collection(json)
app/helpers/application_helper.rb
@@ -41,9 +41,9 @@ module ApplicationHelper
 
   def backbone_collection_for(items)
     render partial: 'backbone_collection', locals: {
-      collection_name: items.model_name.human,
       items: items,
-      partial_name: items.model_name.plural,
+      model_name: items.model_name.human,
+      plural_name: items.model_name.plural,
     }
   end
 end
app/views/application/_backbone_collection.html.erb
@@ -1,5 +1,5 @@
 <% cache items do %>
   <%= javascript_tag do %>
-    csx.AutoCollection.install('<%= collection_name %>', <%= raw render partial: "application/json/#{partial_name}", locals: { items: items } %>);
+    csx.AutoCollection.install('<%= model_name %>', '<%= plural_name %>', <%= raw render partial: "application/json/#{plural_name}", locals: { items: items } %>);
   <% end %>
 <% end %>
spec/javascripts/models/auto_collection_spec.js.coffee
@@ -5,7 +5,7 @@ describe "AutoCollection", ->
 
   describe ".install", ->
     it "installs a categories collection", ->
-      subject.install('Category', [id: 1, name: 'cakes'])
+      subject.install('Category', 'categories', [id: 1, name: 'cakes'])
 
       collection = csx.Collections.Category
       expect(collection).not.toBe(undefined)
@@ -13,15 +13,14 @@ describe "AutoCollection", ->
       expect(collection.first().get('name')).toEqual('cakes')
 
     it "binds the proper model", ->
-      subject.install('Category', [])
+      subject.install('Category', 'categories', [])
       expect(csx.Collections.Category.model).toEqual(csx.Models.Category)
 
     it "binds the proper url", ->
-      subject.install('Cake', [])
+      subject.install('Cake', 'cakes', [])
       expect(csx.Collections.Cake.url).toEqual('/api/v1/cakes')
 
-
-#class csx.Collections.CakesCollection extends Backbone.Collection
-  #model: csx.Models.Cake
-  #url: '/api/v1/cakes'
-
+    it "works for models that do not map to a backbone model", ->
+      subject.install('Tag', 'acts_as_taggable_on_tags', [])
+      expect(csx.Collections.Tag.model).toEqual(Backbone.Model)
+      expect(csx.Collections.Tag.url).toEqual(undefined)