Skip to content

Commit

Permalink
Add simple RestPersistence.read implementation.
Browse files Browse the repository at this point in the history
  • Loading branch information
benpickles committed Aug 18, 2010
1 parent 6cb8d02 commit b0b6e8f
Show file tree
Hide file tree
Showing 3 changed files with 46 additions and 2 deletions.
23 changes: 21 additions & 2 deletions src/model_rest_persistence.js
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,24 @@ Model.RestPersistence = function(resource, methods) {
}
},

read: function(callback) {
var klass = this.klass

return this.xhr("GET", this.read_path(), null, function(success, xhr, data) {
var models = []

for (var i = 0, length = data.length; i < length; i++) {
models.push(new klass(data[i]))
}

callback(models)
})
},

read_path: function() {
return resource
},

update: function(model, callback) {
return this.xhr('PUT', this.update_path(model), model, callback);
},
Expand All @@ -69,7 +87,7 @@ Model.RestPersistence = function(resource, methods) {

xhr: function(method, url, model, callback) {
var self = this;
var data = method === "DELETE" ? null : this.params(model);
var data = ["DELETE", "GET"].indexOf(method) > -1 ? null : this.params(model);

return jQuery.ajax({
type: method,
Expand Down Expand Up @@ -124,7 +142,8 @@ Model.RestPersistence = function(resource, methods) {
}
}, methods)

return function() {
return function(klass) {
rest_persistence.klass = klass
return rest_persistence
}
};
7 changes: 7 additions & 0 deletions test/app.rb
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,13 @@ def json!
File.read("tests/#{params[:name]}")
end

get '/posts' do
JSON.generate([
{ :id => 1, :title => 'Bar' },
{ :id => 2, :title => 'Foo' }
])
end

# Success.
post '/posts' do
json!
Expand Down
18 changes: 18 additions & 0 deletions test/tests/model_rest_persistence.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,23 @@
module("Model.RestPersistence");

asyncTest("read", 3, function() {
var Post = Model("post", {
persistence: Model.RestPersistence("/posts")
})

Post.persistence.read(function(models) {
equals(models.length, 2)

var post1 = models[0]
var post2 = models[1]

same({ id: 1, title: "Bar" }, post1.attributes)
same({ id: 2, title: "Foo" }, post2.attributes)

start()
})
})

test("create with named params in resource path", function() {
var Post = Model("post", {
persistence: Model.RestPersistence("/root/:root_id/nested/:nested_id/posts")
Expand Down

0 comments on commit b0b6e8f

Please sign in to comment.