Module: CouchbaseOrm::Associations::ClassMethods

Defined in:
lib/couchbase-orm/associations.rb

Instance Method Summary collapse

Instance Method Details

#associationsObject



58
59
60
# File 'lib/couchbase-orm/associations.rb', line 58

def associations
    @associations || []
end

#belongs_to(name, **options) ⇒ Object

Defines a belongs_to association for the model



12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
# 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