Sha256: 2910487d5c8f0dcc82e1228e67a0cd1b174045abfaeafdcbb1f4ceeb7026bb38

Contents?: true

Size: 1.66 KB

Versions: 6

Compression:

Stored size: 1.66 KB

Contents

module Rainforest
  module APIOperations
    module Update
      def save
        values = serialize_params(self)

        if @values[:metadata]
          values[:metadata] = serialize_metadata
        end

        if values.length > 0
          values.delete(:id)

          if self.id
            response, api_key = Rainforest.request(:put, url + "/#{self.id}", @api_key, values)
          else
            response, api_key = Rainforest.request(:post, url, @api_key, values)
          end
          refresh_from(response, api_key)
        end
        self
      end

      def serialize_metadata
        if @unsaved_values.include?(:metadata)
          # the metadata object has been reassigned
          # i.e. as object.metadata = {key => val}
          metadata_update = @values[:metadata]  # new hash
          new_keys = metadata_update.keys.map(&:to_sym)
          # remove keys at the server, but not known locally
          keys_to_unset = @previous_metadata.keys - new_keys
          keys_to_unset.each {|key| metadata_update[key] = ''}

          metadata_update
        else
          # metadata is a RainforestObject, and can be serialized normally
          serialize_params(@values[:metadata])
        end
      end

      def serialize_params(obj)
        case obj
        when nil
          ''
        when RainforestObject
          unsaved_keys = obj.instance_variable_get(:@unsaved_values)
          obj_values = obj.instance_variable_get(:@values)
          update_hash = {}

          unsaved_keys.each do |k|
            update_hash[k] = serialize_params(obj_values[k])
          end

          update_hash
        else
          obj
        end
      end
    end
  end
end

Version data entries

6 entries across 6 versions & 1 rubygems

Version Path
rainforest-1.0.7 lib/rainforest/api_operations/update.rb
rainforest-1.0.6 lib/rainforest/api_operations/update.rb
rainforest-1.0.5 lib/rainforest/api_operations/update.rb
rainforest-1.0.4 lib/rainforest/api_operations/update.rb
rainforest-1.0.3 lib/rainforest/api_operations/update.rb
rainforest-1.0.1 lib/rainforest/api_operations/update.rb