Sha256: 8e5ef8acb4ab87574feacbdcb537839e4df9234f7e59944af5693977fa9fdf57

Contents?: true

Size: 1.36 KB

Versions: 22

Compression:

Stored size: 1.36 KB

Contents

module CassandraObject
  module BelongsTo
    class Association
      attr_reader :owner, :reflection
      delegate :options, to: :reflection

      def initialize(owner, reflection)
        @owner = owner
        @reflection = reflection
      end

      def reader
        unless loaded?
          if record_id = owner.send(reflection.foreign_key).presence
            self.record_variable = association_class.find_by_id(record_id)
          else
            self.record_variable = nil
          end
        end

        record_variable
      end

      def writer(record)
        self.record_variable = record
        owner.send("#{reflection.foreign_key}=", record.try(:id))
        if reflection.polymorphic?
          owner.send("#{reflection.polymorphic_column}=", record.class.name)
        end
      end

      def association_class
        association_class_name.constantize
      end

      def association_class_name
        reflection.polymorphic? ? owner.send(reflection.polymorphic_column) : reflection.class_name
      end

      def record_variable
        owner.instance_variable_get(reflection.instance_variable_name)
      end

      def record_variable=(record)
        owner.instance_variable_set(reflection.instance_variable_name, record)
      end

      def loaded?
        owner.instance_variable_defined?(reflection.instance_variable_name)
      end
    end
  end
end

Version data entries

22 entries across 22 versions & 1 rubygems

Version Path
gotime-cassandra_object-3.0.0 lib/cassandra_object/belongs_to/association.rb
gotime-cassandra_object-2.13.0 lib/cassandra_object/belongs_to/association.rb