Module: SimplyStored::Couch::HasAndBelongsToMany

Included in:
ClassMethods
Defined in:
lib/simply_stored/couch/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



152
153
154
155
156
157
158
159
160
161
162
# File 'lib/simply_stored/couch/has_and_belongs_to_many.rb', line 152

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



139
140
141
142
143
144
145
146
147
148
149
150
# File 'lib/simply_stored/couch/has_and_belongs_to_many.rb', line 139

def define_has_and_belongs_to_many_count(name, options, through = nil)
  method_name = name.to_s.singularize.underscore + "_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



68
69
70
71
72
73
74
75
76
77
78
79
80
81
# File 'lib/simply_stored/couch/has_and_belongs_to_many.rb', line 68

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 = extract_association_options(local_options)

    cached_results = send("_get_cached_#{name}")
    cache_key = _cache_key_for(local_options)
    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])
      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
# File 'lib/simply_stored/couch/has_and_belongs_to_many.rb', line 9

def define_has_and_belongs_to_many_property(foreign_key)
  property foreign_key
end

#define_has_and_belongs_to_many_setter_add(name, options) ⇒ Object



83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
# File 'lib/simply_stored/couch/has_and_belongs_to_many.rb', line 83

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



102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
# File 'lib/simply_stored/couch/has_and_belongs_to_many.rb', line 102

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



129
130
131
132
133
134
135
136
137
# File 'lib/simply_stored/couch/has_and_belongs_to_many.rb', line 129

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



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
59
60
61
62
63
64
65
66
# File 'lib/simply_stored/couch/has_and_belongs_to_many.rb', line 13

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]}"

  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_#{self.name.underscore}_has_and_belongs_to_many_#{name}",
    :map => map_definition_without_deleted,
    :reduce => 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}_has_and_belongs_to_many_#{name}_with_deleted",
    :map => map_definition_with_deleted,
    :reduce => reduce_definition,
    :type => "custom",
    :include_docs => true
end

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



4
5
6
7
# File 'lib/simply_stored/couch/has_and_belongs_to_many.rb', line 4

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