Method: DataMapper::Persevere::Adapter#create

Defined in:
lib/persevere_adapter/adapter.rb

#create(resources) ⇒ Integer

Used by DataMapper to put records into a data-store: “INSERT” in SQL-speak. It takes an array of the resources (model instances) to be saved. Resources each have a key that can be used to quickly look them up later without searching, if the adapter supports it.

Parameters:

  • resources (Array<DataMapper::Resource>)

    The set of resources (model instances)

Returns:

  • (Integer)

    The number of records that were actually saved into the data-store



58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
# File 'lib/persevere_adapter/adapter.rb', line 58

def create(resources)
  connect if @persevere.nil?
  created = 0
  
  check_schemas
  
  resources.each do |resource|
    resource = Persevere.enhance(resource)
    serial = resource.model.serial(self.name)
    path = "/#{resource.model.storage_name}/"
    # Invoke to_json_hash with a boolean to indicate this is a create
    # We might want to make this a post-to_json_hash cleanup instead
    payload = resource.to_json_hash.delete_if{|key,value| value.nil? }
    DataMapper.logger.debug("(Create) PATH/PAYLOAD: #{path} #{payload.inspect}")
    response = @persevere.create(path, payload)

    # Check the response, this needs to be more robust and raise
    # exceptions when there's a problem
    if response.code == "201"# good:
      rsrc_hash = JSON.parse(response.body)
      # Typecast attributes, DM expects them properly cast
      resource.model.properties.each do |prop|
        value = rsrc_hash[prop.field.to_s]
        rsrc_hash[prop.field.to_s] = prop.typecast(value) unless value.nil?
        # Shift date/time objects to the correct timezone because persevere is UTC
        case prop 
          when DateTime then rsrc_hash[prop.field.to_s] = value.new_offset(Rational(Time.now.getlocal.gmt_offset/3600, 24))
          when Time then rsrc_hash[prop.field.to_s] = value.getlocal
        end
      end
      
      serial.set!(resource, rsrc_hash["id"]) unless serial.nil?

      created += 1
    else
      return false
    end
  end

  # Return the number of resources created in persevere.
  return created
end