Module: Mongo::Model::AttachmentsHelper

Defined in:
lib/kit/models/attachments_helper.rb

Defined Under Namespace

Modules: ClassMethods Classes: FileHelper

Instance Method Summary collapse

Instance Method Details

#get_attachments(association_name, field_name) ⇒ Object



25
26
27
28
29
# File 'lib/kit/models/attachments_helper.rb', line 25

def get_attachments association_name, field_name
  send(association_name).
    sort{|a, b| a.send(field_name).file.name <=> b.send(field_name).file.name}.
    collect{|o| {name: o.send(field_name).file.name, url: o.send(field_name).url}.to_openobject}
end

#set_attachments(association_name, field_name, values, &block) ⇒ Object



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
# File 'lib/kit/models/attachments_helper.rb', line 31

def set_attachments association_name, field_name, values, &block
  association = send(association_name)
  existing_names = association.collect{|o| o.send(field_name).file.name}.sort

  add = values.select do |o|
    h = FileHelper.new o
    h.file? and !existing_names.include?(h.name)
  end
  update = values.select do |o|
    h = FileHelper.new o
    h.file? and existing_names.include?(h.name)
  end
  remove = association.select do |model|
    values.none? do |o|
      h = FileHelper.new o
      model.send(field_name).name == h.name
    end
  end

  add.each do |file|
    model = block.call
    model._parent = self
    model.send "#{field_name}=", file
    association << model
  end
  update.each do |file|
    h = FileHelper.new file
    association.each do |model|
      if model.send(field_name).file.name == h.name
        model.send "#{field_name}=", file
        break
      end
    end
  end
  remove.each do |model|
    association.delete model
    # association.where(_id: model._id).destroy_all
  end
end