Module: SimpleAttachments::ContainerModel::Helpers

Defined in:
lib/simple_attachments/container_model.rb

Instance Method Summary collapse

Instance Method Details

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

Mark model as container and create association.

Syntax is identical to has_many.

has_many_attachments :attachments


11
12
13
14
15
16
17
18
19
20
21
22
23
# File 'lib/simple_attachments/container_model.rb', line 11

def has_many_attachments(name, options = {})
  reflection = has_many name, options
  send(:define_method, reflection.plural_name + '_=') do |attachment_ids|
    method, model = recover_vars(__method__)
    old_attachment_ids = send method.singularize.concat('_ids')
    attachment_ids = attachment_ids.map { |id| id.to_i }
    model.destroy_all :id => (old_attachment_ids - attachment_ids)
    (attachment_ids - old_attachment_ids).each do |attachment_id|
      find_and_add_attachment(method, model, attachment_id)
    end
  end
  send :include, InstanceMethods
end

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

Mark model as container and create association.

Syntax is identical to has_one.

has_one_attachment :attachment


31
32
33
34
35
36
37
38
# File 'lib/simple_attachments/container_model.rb', line 31

def has_one_attachment(name, options = {})
  reflection = has_one name, options
  send(:define_method, reflection.name.to_s + '_=') do |attachment_id|
    method, model = recover_vars(__method__)
    find_and_add_attachment(method, model, attachment_id)
  end
  send :include, InstanceMethods
end