Module: SimplyCouch::Model::BelongsTo

Included in:
ClassMethods
Defined in:
lib/simply_couch/model/belongs_to.rb

Defined Under Namespace

Classes: Property

Instance Method Summary collapse

Instance Method Details

#belongs_to(name, options = {}) ⇒ Object



6
7
8
9
10
11
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
57
58
# File 'lib/simply_couch/model/belongs_to.rb', line 6

def belongs_to(name, options = {})
  check_existing_properties(name, SimplyCouch::Model::BelongsTo::Property)
  association_property = if name.to_s.index('__')
                           # Already defined properly
                           name
                         elsif options[:class_name].present?
                           # Determine namespace and replace last argument with given name
                           name_hierarchy = options[:class_name].to_s.underscore.split(/\/|::/)
                           name_hierarchy[-1] = name
                           name_hierarchy.join('__')
                         elsif rindex = foreign_property.to_s.rindex('__')
                           # Make name based on current namespace
                           "#{foreign_property[0...rindex]}__#{name}"
                         else
                           # Just return the good old name
                           name
                         end

  map_definition_without_deleted = <<-eos
    function(doc) {
      if (doc['ruby_class'] == '#{self.to_s}' && doc['#{name}_id'] != null) {
        if (doc['#{soft_delete_attribute}'] && doc['#{soft_delete_attribute}'] != null){
          // "soft" deleted
        }else{
          emit([doc.#{name}_id, doc.created_at], 1);
        }
      }
    }
  eos

  reduce_definition = "_sum"
  view "association_#{foreign_property}_belongs_to_#{association_property}",
    :map_function => map_definition_without_deleted,
    :reduce_function => reduce_definition,
    :type => :custom,
    :include_docs => true

  map_definition_with_deleted = <<-eos
    function(doc) {
      if (doc['ruby_class'] == '#{self.to_s}' && doc['#{name}_id'] != null) {
        emit([doc.#{name}_id, doc.created_at], 1);
      }
    }
  eos

  view "association_#{foreign_property}_belongs_to_#{association_property}_with_deleted",
    :map_function => map_definition_with_deleted,
    :reduce_function => reduce_definition,
    :type => :custom,
    :include_docs => true

  properties << SimplyCouch::Model::BelongsTo::Property.new(self, name, options)
end