Module: SimplyCouch::Model::HasAndBelongsToMany

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

Defined Under Namespace

Classes: Property

Instance Method Summary collapse

Instance Method Details

#define_has_and_belongs_to_many_after_destroy_cleanup(name, options) ⇒ Object



173
174
175
176
177
178
179
180
181
182
183
# File 'lib/simply_couch/model/has_and_belongs_to_many.rb', line 173

def define_has_and_belongs_to_many_after_destroy_cleanup(name, options)
  if options[:class_storing_keys] == self.name
    define_method "has_and_belongs_to_many_clean_up_after_destroy" do |property|
      nil # deleting is enough as we store the keys
    end
  else
    define_method "has_and_belongs_to_many_clean_up_after_destroy" do |property|
      send("remove_all_#{property.name}")
    end
  end
end

#define_has_and_belongs_to_many_count(name, options, through = nil) ⇒ Object



160
161
162
163
164
165
166
167
168
169
170
171
# File 'lib/simply_couch/model/has_and_belongs_to_many.rb', line 160

def define_has_and_belongs_to_many_count(name, options, through = nil)
  method_name = name.to_s.singularize.underscore.gsub('/', '__') + "_count"
  define_method(method_name) do |*args|
    local_options = args.first && args.first.is_a?(Hash) && args.first
    forced_reload, with_deleted, limit, descending = extract_association_options(local_options)

    if forced_reload || instance_variable_get("@#{method_name}").nil?
      instance_variable_set("@#{method_name}", count_associated_via_join_view(through || options[:class_name], self.class, :with_deleted => with_deleted, :foreign_key => options[:foreign_key]))
    end
    instance_variable_get("@#{method_name}")
  end
end

#define_has_and_belongs_to_many_getter(name, options) ⇒ Object



88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
# File 'lib/simply_couch/model/has_and_belongs_to_many.rb', line 88

def define_has_and_belongs_to_many_getter(name, options)
  define_method(name) do |*args|
    local_options = args.first && args.first.is_a?(Hash) && args.first
    forced_reload, with_deleted, limit, descending, skip = extract_association_options(local_options)

    cached_results = send("_get_cached_#{name}")
    cache_key = _cache_key_for(local_options)
    return cached_results[cache_key] || [] unless persisted?
    if forced_reload || cached_results[cache_key].nil?
      cached_results[cache_key] = find_associated_via_join_view(options[:class_name], self.class, :with_deleted => with_deleted, :limit => limit, :descending => descending, :foreign_key => options[:foreign_key], :skip => skip)
      instance_variable_set("@#{name}", cached_results)
    end
    cached_results[cache_key]
  end
end

#define_has_and_belongs_to_many_property(foreign_key) ⇒ Object



9
10
11
12
13
14
15
16
# File 'lib/simply_couch/model/has_and_belongs_to_many.rb', line 9

def define_has_and_belongs_to_many_property(foreign_key)
  property foreign_key

  # Only allow non nil or empty values to be set
  define_method "#{foreign_key}=" do |value|
    super(value.is_a?(Array) ? value.select{|v| v.present?} : value)
  end
end

#define_has_and_belongs_to_many_setter_add(name, options) ⇒ Object



104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
# File 'lib/simply_couch/model/has_and_belongs_to_many.rb', line 104

def define_has_and_belongs_to_many_setter_add(name, options)
  define_method("add_#{name.to_s.singularize}") do |value|
    klass = self.class.get_class_from_name(name)
    raise ArgumentError, "expected #{klass} got #{value.class}" unless value.is_a?(klass)

    if options[:class_storing_keys] == self.class.name
      self.send("#{options[:foreign_key]}=", ((send(options[:foreign_key]) || []) + [value.id]).uniq )
      self.save(false)
    else
      value.send("#{options[:foreign_key]}=", ((value.send(options[:foreign_key]) || []) + [self.id]).uniq )
      value.save(false)
    end

    cached_results = send("_get_cached_#{name}")[:all]
    send("_set_cached_#{name}", (cached_results || []) << value, :all)
    nil
  end
end

#define_has_and_belongs_to_many_setter_remove(name, options) ⇒ Object



123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
# File 'lib/simply_couch/model/has_and_belongs_to_many.rb', line 123

def define_has_and_belongs_to_many_setter_remove(name, options)
  define_method "remove_#{name.to_s.singularize}" do |value|
    klass = self.class.get_class_from_name(name)
    raise ArgumentError, "expected #{klass} got #{value.class}" unless value.is_a?(klass)

    if options[:class_storing_keys] == self.class.name
      raise ArgumentError, "cannot remove not mine" unless (send(options[:foreign_key]) || []).include?(value.id)
    else
      raise ArgumentError, "cannot remove not mine" unless (value.send(options[:foreign_key]) || []).include?(id)
    end

    if options[:class_storing_keys] == self.class.name
      foreign_keys = (send(options[:foreign_key]) || []) - [value.id]
      send("#{options[:foreign_key]}=", foreign_keys)
      save(false)
    else
      foreign_keys = (value.send(options[:foreign_key]) || []) - [self.id]
      value.send("#{options[:foreign_key]}=", foreign_keys)
      value.save(false)
    end

    cached_results = send("_get_cached_#{name}")[:all]
    send("_set_cached_#{name}", (cached_results || []).delete_if{|item| item.id == value.id}, :all)
    nil
  end
end

#define_has_and_belongs_to_many_setter_remove_all(name, options) ⇒ Object



150
151
152
153
154
155
156
157
158
# File 'lib/simply_couch/model/has_and_belongs_to_many.rb', line 150

def define_has_and_belongs_to_many_setter_remove_all(name, options)
  define_method "remove_all_#{name}" do
    all = send("#{name}", :force_reload => true)

    all.collect{|i| i}.each do |item|
      send("remove_#{name.to_s.singularize}", item)
    end
  end
end

#define_has_and_belongs_to_many_views(name, options) ⇒ Object



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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
# File 'lib/simply_couch/model/has_and_belongs_to_many.rb', line 18

def define_has_and_belongs_to_many_views(name, options)
  key_order = options[:class_storing_keys] == self.name ? "doc.#{options[:foreign_key]}[index], doc._id" : "doc._id, doc.#{options[:foreign_key]}[index]"
  value = options[:class_storing_keys] == self.name ? 1 : "{ _id :doc.#{options[:foreign_key]}[index]}"
  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'] == '#{options[:class_storing_keys]}' && doc['#{options[:foreign_key]}'] != null) {
        if (doc['#{soft_delete_attribute}'] && doc['#{soft_delete_attribute}'] != null){
          // "soft" deleted
        }else{
          for (var index in doc.#{options[:foreign_key]}) {
            emit([#{key_order}], #{value});
          }
        }
      }
    }
  eos

  reduce_definition = options[:class_storing_keys] == self.name ? "_sum" : <<-eos
    function(key, values) {
      var sum = 0;
      for (var i in values){
        if (typeof(i) == 'number'){
          sum = sum + i;
        } else {
          sum = sum + 1;
        }
      }
      return sum;
    }
  eos

  view "association_#{foreign_property}_has_and_belongs_to_many_#{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'] == '#{options[:class_storing_keys]}' && doc['#{options[:foreign_key]}'] != null) {
        for (var index in doc.#{options[:foreign_key]}) {
          emit([#{key_order}], #{value});
        }
      }
    }
  eos

  view "association_#{self.name.underscore.gsub('/', '__')}_has_and_belongs_to_many_#{name}_with_deleted",
    :map_function => map_definition_with_deleted,
    :reduce_function => reduce_definition,
    :type => :custom,
    :include_docs => true
end

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



4
5
6
7
# File 'lib/simply_couch/model/has_and_belongs_to_many.rb', line 4

def has_and_belongs_to_many(name, options = {})
  check_existing_properties(name, SimplyCouch::Model::HasAndBelongsToMany::Property)
  properties << SimplyCouch::Model::HasAndBelongsToMany::Property.new(self, name, options)
end