Permalink
Browse files

Refactor YAML adapter #create method to push max id calculation to a …

…separate method

* Add conditional so that the code does not blow up when there is no serial
  property in the model.
  • Loading branch information...
1 parent a8168b2 commit 9f4cc13d3efb51cc3138a66a394a9864a0e40e03 @dkubb dkubb committed Apr 8, 2012
Showing with 25 additions and 9 deletions.
  1. +25 −9 lib/dm-yaml-adapter/adapter.rb
@@ -8,16 +8,9 @@ class YamlAdapter < AbstractAdapter
def create(resources)
model = resources.first.model
update_records(model) do |records|
+ max_id = max_id_for(model, records)
resources.each do |resource|
- # Generating next ID
- # FIXME:
- # * This does not work for CPK's
- # * Inefficent for large datasets.
- highest_id = records.map do |record|
- serial = model.serial(name)
- record.fetch(serial.field)
- end.max
- initialize_serial(resource, (highest_id || 0).succ)
+ initialize_serial(resource, max_id += 1)
records << attributes_as_fields(resource.attributes(nil))
end
end
@@ -122,6 +115,29 @@ def yaml_file(model)
@path.join("#{model.storage_name(name)}.yml")
end
+ # Get the maximum id to use as a base when creating new records
+ #
+ # @param [DataMapper::Model] model
+ #
+ # @param [Hash] records
+ #
+ # @return [Integer]
+ #
+ # @api private
+ def max_id_for(model, records)
+ serial = model.serial(name)
+
+ # Generating next ID
+ # FIXME:
+ # * This does not work for CPK's
+ # * Inefficent for large datasets.
+ if serial
+ records.map { |record| record.fetch(serial.field) }.max || 0
+ else
+ records.size
+ end
+ end
+
end # class YamlAdapter
const_added(:YamlAdapter)

0 comments on commit 9f4cc13

Please sign in to comment.