motion-prime/models/sync.rb in motion-prime-0.3.1 vs motion-prime/models/sync.rb in motion-prime-0.3.2

- old
+ new

@@ -114,10 +114,11 @@ self.send(:"fetch_#{key}", value) elsif respond_to?(:"#{key}=") self.send(:"#{key}=", value) end end + self end def fetch_associations(sync_options = {}, &block) use_callback = block_given? associations = self.class._associations || {} @@ -151,12 +152,12 @@ def fetch_has_many(key, options = {}, sync_options = {}, &block) old_collection = self.send(key) use_callback = block_given? puts "SYNC: started sync for #{key} in #{self.class_name_without_kvo}" - api_client.get normalize_sync_url(options[:sync_url]) do |data, status_code| - data = data[options[:sync_key]] if options[:sync_key] + api_client.get normalize_sync_url(options[:sync_url]) do |response, status_code| + data = options.has_key?(:sync_key) ? response[options[:sync_key]] : response if data # Update/Create existing records data.each do |attributes| model = old_collection.detect{ |model| model.id == attributes[:id]} unless model @@ -172,35 +173,35 @@ old_model.delete end end save if sync_options[:save] puts "SYNC: finished sync for #{key} in #{self.class_name_without_kvo}" - block.call(data, status_code) if use_callback + block.call(data, status_code, response) if use_callback else puts "SYNC ERROR: failed sync for #{key} in #{self.class_name_without_kvo}" - block.call(data, status_code) if use_callback + block.call(data, status_code, response) if use_callback end end end def fetch_has_one(key, options = {}, &block) use_callback = block_given? puts "SYNC: started sync for #{key} in #{self.class_name_without_kvo}" - api_client.get normalize_sync_url(options[:sync_url]) do |data, status_code| - data = data[options[:sync_key]] if options[:sync_key] + api_client.get normalize_sync_url(options[:sync_url]) do |response, status_code| + data = options.has_key?(:sync_key) ? response[options[:sync_key]] : response if data.present? model = self.send(key) unless model model = key.singularize.to_s.classify.constantize.new self.send(:"#{key}_bag") << model end model.fetch_with_attributes(data) model.save if sync_options[:save] - block.call(data, status_code) if use_callback + block.call(data, status_code, response) if use_callback else puts "SYNC ERROR: failed sync for #{key} in #{self.class_name_without_kvo}" - block.call(data, status_code) if use_callback + block.call(data, status_code, response) if use_callback end end end def filtered_updatable_attributes(options = {}) @@ -238,9 +239,17 @@ url.to_s.gsub(':id', id.to_s) end end module ModelSyncClassMethods + def new(data = {}, options = {}) + model = super + if fetch_attributes = options[:fetch_attributes] + model.fetch_with_attributes(fetch_attributes) + end + model + end + def sync_url(url = nil, &block) if url || block_given? self._sync_url = url || block else self._sync_url \ No newline at end of file