Sha256: f3f0b3cfd2c5aa4bb64acf48c264fe9512ec3108636b3c0c19d5d961846acab3

Contents?: true

Size: 1.71 KB

Versions: 2

Compression:

Stored size: 1.71 KB

Contents

module SparkApi
  module Models
    module Concerns

      module Savable

        def save(arguments = {})
          self.errors = [] # clear the errors hash
          begin
            return save!(arguments)
          rescue BadResourceRequest => e
            self.errors << {:code => e.code, :message => e.message}
            SparkApi.logger.error("Failed to save resource #{self}: #{e.message}")
          rescue NotFound => e
            SparkApi.logger.error("Failed to save resource #{self}: #{e.message}")
          end
          false
        end
        def save!(arguments = {})
          persisted? ? update!(arguments) : create!(arguments)
        end

        def create!(arguments = {})
          results = connection.post self.path, post_data.merge(params_for_save), arguments
          update_resource_identifiers(results.first)
          reset_dirty
          params_for_save.clear
          true
        end

        def update!(arguments = {})
          return true unless changed? && persisted?
          connection.put resource_uri, dirty_attributes, arguments
          reset_dirty
          params_for_save.clear
          true
        end

        def params_for_save
          @params_for_save ||= {}
        end

        private 

        def update_resource_identifiers(result)
          attributes['ResourceUri'] = result['ResourceUri']
          attributes['Id'] = result['Id'] ? result['Id'] : parse_id(result['ResourceUri'])
        end

        # can be overridden
        def resource_pluralized
          resource = self.class.name.split('::').last
          unless resource.split('').last == "s"
            resource = resource + "s"
          end
          resource
        end

      end

    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
spark_api-1.3.1 lib/spark_api/models/concerns/savable.rb
spark_api-1.3.0 lib/spark_api/models/concerns/savable.rb