module CouchbaseOrm::Associations::ClassMethods

Public Instance Methods

associations() click to toggle source
# File lib/couchbase-orm/associations.rb, line 58
def associations
    @associations || []
end
belongs_to(name, **options) click to toggle source

Defines a belongs_to association for the model

# File lib/couchbase-orm/associations.rb, line 12
def belongs_to(name, **options)
    @associations ||= []
    @associations << [name.to_sym, options[:dependent]]

    ref = options[:foreign_key] || :"#{name}_id"
    ref_ass = :"#{ref}="
    instance_var = :"@__assoc_#{name}"

    # Class reference
    assoc = (options[:class_name] || name.to_s.camelize).to_s

    # Create the local setter / getter
    attribute(ref) { |value|
        remove_instance_variable(instance_var) if instance_variable_defined?(instance_var)
        value
    }

    # Define reader
    define_method(name) do
        return instance_variable_get(instance_var) if instance_variable_defined?(instance_var)
        val = if options[:polymorphic]
            ::CouchbaseOrm.try_load(self.send(ref))
        else
            assoc.constantize.find(self.send(ref), quiet: true)
        end
        instance_variable_set(instance_var, val)
        val
    end

    # Define writer
    attr_writer name
    define_method(:"#{name}=") do |value|
        if value
            if !options[:polymorphic]
                klass = assoc.constantize
                raise ArgumentError, "type mismatch on association: #{klass.design_document} != #{value.class.design_document}" if klass.design_document != value.class.design_document
            end
            self.send(ref_ass, value.id)
        else
            self.send(ref_ass, nil)
        end

        instance_variable_set(instance_var, value)
    end
end