Skip to content

Instantly share code, notes, and snippets.

@spnkr
Created March 26, 2016 21:14
Show Gist options
  • Save spnkr/4c3247c1e11101fabad1 to your computer and use it in GitHub Desktop.
Save spnkr/4c3247c1e11101fabad1 to your computer and use it in GitHub Desktop.
sync coredata with firebase in rubymotion using NSAsynchronousFetchRequest. works with large data sets. uses the cdq and motion-firebase gem.
class AppDelegate
def post_messages_firebase
@_post_messages_firebase ||= "post_messages".fbase
end
end
class SomeViewController < UIViewController
def viewDidDisappear(animated=true)
super
adg.post_messages_firebase.removeAllObservers
end
def viewWillAppear(animated=true)
super
subscribe_to_fb
end
def subscribe_to_fb
adg.post_messages_firebase.on(:added) do |snapshot|
load_a_post_via_cd(snapshot.key.to_i,snapshot.value)
end
adg.post_messages_firebase.on(:changed) do |snapshot|
load_a_post_via_cd(snapshot.key.to_i,snapshot.value)
end
adg.post_messages_firebase.on(:removed) do |snapshot|
po = Post.where(id:snapshot.key.to_i)
if po.count > 0
po = po.first
po.destroy
end
end
#this is only called after ALL add/remove/delete events above are called
adg.post_messages_firebase.once(:value) do |snapshot|
:finished_inital_load.post_notification(nil)
end
end
def load_a_post_via_cd(id,props,delete_me=false)
fetchRequest = NSFetchRequest.alloc.initWithEntityName('Post')
fetchRequest.predicate = NSPredicate.predicateWithFormat("id==%@",id)
asyncFetch = NSAsynchronousFetchRequest.alloc.initWithFetchRequest(fetchRequest, completionBlock:lambda{|result|
if result.finalResult.count == 0
#ok if this method is slow; doesn't lock the main ui thread
po = Post.find_or_create_by_id(id,withProperties:props)
else
po = result.finalResult.first
end
po.destroy if delete_me
})
error_ptr = Pointer.new(:object)
cdq.contexts.all.last.executeRequest(asyncFetch,error:error_ptr)
end
end
class Fbase
def self.refs
@refs ||= []
end
def self.ref(p)
f = Firebase.new("https://your-name-here.firebaseio.com/#{p}")
if !f.authenticated?
f.authenticate('your-key-here') do |err,auth_d|
end
end
Fbase.refs.push f
f
end
end
class String
def fbase
Fbase.ref self.to_s
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment