Skip to content
Browse files

behaviors for errors in AR methods

support cases where a) request fails b) response is malformed (i.e. neither hash nor array)
  • Loading branch information...
1 parent 4bb95c2 commit 0716d55b54ef50fc5f9fb000094b37804aaa93f9 @clayallsopp committed
Showing with 59 additions and 17 deletions.
  1. +27 −14 lib/remote_model/record.rb
  2. +32 −3 spec/requests_spec.rb
View
41 lib/remote_model/record.rb
@@ -5,27 +5,40 @@ class RemoteModel
class << self
def find(id, params = {}, &block)
get(member_url.format(params.merge(id: id))) do |response, json|
- obj = self.new(json)
- request_block_call(block, obj, response)
+ if response.ok?
+ obj = self.new(json)
+ request_block_call(block, obj, response)
+ else
+ request_block_call(block, nil, response)
+ end
end
end
def find_all(params = {}, &block)
get(collection_url.format(params)) do |response, json|
- objs = []
- arr_rep = nil
- if json.class == Array
- arr_rep = json
- elsif json.class == Hash
- plural_sym = self.pluralize.to_sym
- if json.has_key? plural_sym
- arr_rep = json[plural_sym]
+ if response.ok?
+ objs = []
+ arr_rep = nil
+ if json.class == Array
+ arr_rep = json
+ elsif json.class == Hash
+ plural_sym = self.pluralize.to_sym
+ if json.has_key? plural_sym
+ arr_rep = json[plural_sym]
+ end
+ else
+ # the returned data was something else
+ # ie a string, number
+ request_block_call(block, nil, response)
+ return
end
+ arr_rep.each { |one_obj_hash|
+ objs << self.new(one_obj_hash)
+ }
+ request_block_call(block, objs, response)
+ else
+ request_block_call(block, nil, response)
end
- arr_rep.each { |one_obj_hash|
- objs << self.new(one_obj_hash)
- }
- request_block_call(block, objs, response)
end
end
View
35 spec/requests_spec.rb
@@ -1,14 +1,43 @@
+class FailingModel < RemoteModule::RemoteModel
+ def self.root_url
+ # returns a 400 when you don't have a proper token
+ "http://graph.facebook.com/btaylor/friends"
+ end
+
+ collection_url ""
+ member_url "/:id"
+end
+
describe "The requests stuff" do
it "should parse json" do
- ran = false
+ @ran = false
RemoteModule::RemoteModel.get("http://graph.facebook.com/btaylor") do |response, json|
json.class.should == Hash
response.ok?.should == true
- ran = true
+ @ran = true
end
# really stupid, haven't made an async request example...
wait 5.0 do
- ran.should == true
+ @ran.should == true
+ end
+ end
+
+ it "should return nil upon bad requests" do
+ @ran_find_all = false
+ @ran_find = false
+ FailingModel.find_all do |results, response|
+ results.should == nil
+ @ran_find_all = true
+ end
+
+ FailingModel.find("1") do |result, response|
+ result.should == nil
+ @ran_find = true
+ end
+
+ wait 5.0 do
+ @ran_find_all.should == true
+ @ran_find.should == true
end
end
end

0 comments on commit 0716d55

Please sign in to comment.
Something went wrong with that request. Please try again.