Sha256: 3d41f49fc17cbe8734247fc9abda5c9f61e8abff348ea4bc6e2b024281c88a24

Contents?: true

Size: 1.53 KB

Versions: 3

Compression:

Stored size: 1.53 KB

Contents

module GdatastoreMapper
  module Persistence

    def save
      return false if !valid?
      run_callbacks :save do
        entity = to_entity
        GdatastoreMapper::Session.dataset.save(entity)
        self.id = entity.key.id
        update_owner(self, :add)
        true
      end
    end

    def update attributes
      return false if !valid?
      run_callbacks :update do
        attributes.each do |name, value|
          send "#{name}=", value if respond_to? "#{name}="
        end
        save
      end
    end

    def destroy
      run_callbacks :destroy do
        update_owner(self, :delete)
        GdatastoreMapper::Session.dataset.delete \
          Google::Cloud::Datastore::Key.new self.class.to_s, id
      end
    end

    def delete
      destroy
    end

    def persisted?
      id.present?
    end

    private

    def update_owner belonging, flg = :add
      return if self.class.belongs_to_models.nil?
      belongings_id = belonging.class.to_s.pluralize.underscore + '_id'
      self.class.belongs_to_models.each do |owner|
        return unless owner_record = belonging.send(owner)
        existing_ids = owner_record.send(belongings_id) || []
        owner_record.update(owner_attr(belongings_id, existing_ids, flg))
      end
    end

    def owner_attr belongings_id, existing_ids, flg
      owner_attr = {}
      if flg == :add
        existing_ids << self.id
      elsif flg == :delete
        existing_ids.delete(self.id)
      end
      owner_attr[belongings_id] = (existing_ids.uniq)
      owner_attr
    end

  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
gdatastore_mapper-0.1.8 lib/gdatastore_mapper/persistence.rb
gdatastore_mapper-0.1.7 lib/gdatastore_mapper/persistence.rb
gdatastore_mapper-0.1.6 lib/gdatastore_mapper/persistence.rb