Sha256: 407c33e7632467f6f51b960e8b3efee365d407b4a819566208eb83ce967f12d3

Contents?: true

Size: 1.2 KB

Versions: 3

Compression:

Stored size: 1.2 KB

Contents

module PassiveRecord
  module Associations
    class HasOneAssociation < Struct.new(:parent_class, :child_class_name, :child_name_sym)
      def to_relation(parent_model)
        HasOneRelation.new(self, parent_model)
      end

      def target_name_symbol
        child_name_sym
      end
    end

    class Relation < Struct.new(:association, :parent_model)
      def singular?
        true
      end
    end

    class HasOneRelation < Relation
      def lookup
        child_class.find_by(parent_model_id_field => parent_model.id)
      end

      def create(attrs={})
        child_class.create(
          attrs.merge(
            parent_model_id_field => parent_model.id
          )
        )
      end

      def lookup_or_create
        lookup || create
      end

      def parent_model_id_field
        association.parent_class.name.demodulize.underscore + "_id"
      end

      def child_class
	module_name = association.parent_class.name.deconstantize
	module_name = "Object" if module_name.empty?
	(module_name.constantize).const_get(association.child_class_name.singularize)
      end

      def id
        parent_model.id
      end

      def child_class_name
        child_class.name
      end
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
passive_record-0.4.5 lib/passive_record/associations/has_one.rb
passive_record-0.4.4 lib/passive_record/associations/has_one.rb
passive_record-0.4.3 lib/passive_record/associations/has_one.rb