Sha256: 25ee998d444756f07ecfdc55e69bec9f97b319e7e6cacffc8e571e6d13142ad4

Contents?: true

Size: 1.68 KB

Versions: 2

Compression:

Stored size: 1.68 KB

Contents

require 'og/relation'

module Og

# A refers to relation. Stores the foreign key in the object.
#--
# TODO: No need to save user (should only call save aspects, for
# example sweepers)
#
# THINK: Investigate if we should only store the key in the 
# foreign object.
#++

class RefersTo < Relation

  def self.foreign_key(rel)
    "#{rel[:foreign_name] || rel[:target_singular_name]}_#{rel[:target_class].primary_key}"
  end

  def enchant
    raise "#{target_singular_name} in #{owner_class} refers to an undefined class" if target_class.nil?
    
    self[:foreign_key] = "#{foreign_name || target_singular_name}_#{target_class.primary_key}"

    if self[:field]
      field = ", :field => :#{self[:field]}"
    end 

    target_primary_key_class = target_class.ann(target_class.primary_key).class
    
    join_table_info = owner_class.ogmanager.store.join_table_info(self)
    owner_key = join_table_info[:owner_key]
    
    owner_class.module_eval %{
      attr_accessor :#{target_singular_name}
      attr_accessor :#{foreign_key}, #{target_primary_key_class}#{field}, :relation => true

      def #{target_singular_name}(reload = false)
        return nil if @#{foreign_key}.nil? 

        # will reload if forced or first load or
        if reload or not @#{target_singular_name}
          @#{target_singular_name} = #{target_class}[@#{foreign_key}]
        end
        @#{target_singular_name}
      end

      def #{target_singular_name}=(obj)
        if obj
          @#{foreign_key} = obj.#{target_class.primary_key}
          obj.#{owner_key} = pk if obj.respond_to?(:#{owner_key}=)
          # obj.save
          save unless self.unsaved?
        end
        return obj
      end
    }    
  end

end

end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
og-0.41.0 lib/og/relation/refers_to.rb
og-0.40.0 lib/og/relation/refers_to.rb