Sha256: 67c571abbcd8bb8cc897099635e30dbe4d2c2027393a0bee6fed4d25f2a38b2a

Contents?: true

Size: 1.67 KB

Versions: 5

Compression:

Stored size: 1.67 KB

Contents

# encoding: utf-8
module Dynamoid #:nodoc:

  module Associations
    module SingleAssociation
      include Association

      delegate :class, :to => :target

      def setter(object)
        delete
        source.update_attribute(source_attribute, Set[object.hash_key])
        self.send(:associate_target, object) if target_association
        object
      end

      def delete
        source.update_attribute(source_attribute, nil)
        self.send(:disassociate_target, target) if target && target_association
        target
      end

      def create!(attributes = {})
        setter(target_class.create!(attributes))
      end

      def create(attributes = {})
        setter(target_class.create(attributes))
      end


      # Is this object equal to the association's target?
      #
      # @return [Boolean] true/false
      #
      # @since 0.2.0
      def ==(other)
        target == other
      end

      # Delegate methods we don't find directly to the target.
      #
      # @since 0.2.0
      def method_missing(method, *args)
        if target.respond_to?(method)
          target.send(method, *args)
        else
          super
        end
      end

      def nil?
        target.nil?
      end

      def empty?
        # This is needed to that ActiveSupport's #blank? and #present?
        # methods work as expected for SingleAssociations.
        target.nil?
      end

      private

      # Find the target of the has_one association.
      #
      # @return [Dynamoid::Document] the found target (or nil if nothing)
      #
      # @since 0.2.0
      def find_target
        return if source_ids.empty?
        target_class.find(source_ids.first)
      end
    end
  end
end

Version data entries

5 entries across 5 versions & 1 rubygems

Version Path
dynamoid-1.3.4 lib/dynamoid/associations/single_association.rb
dynamoid-1.3.3 lib/dynamoid/associations/single_association.rb
dynamoid-1.3.2 lib/dynamoid/associations/single_association.rb
dynamoid-1.3.1 lib/dynamoid/associations/single_association.rb
dynamoid-1.3.0 lib/dynamoid/associations/single_association.rb