Module: Bulldog::HasAttachment::InstanceMethods

Defined in:
lib/bulldog/has_attachment.rb

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.included(base) ⇒ Object



24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
# File 'lib/bulldog/has_attachment.rb', line 24

def self.included(base)
  base.instance_variable_set(:@attachment_reflections, {})

  # We need to store the attachment changes ourselves, since
  # they're unavailable in an after_save.
  base.before_save :store_original_attachments
  base.after_save :save_attachments
  base.after_save :clear_original_attachments

  base.before_save :update_attachment_timestamps
  base.after_destroy :destroy_attachments

  # Force initialization of attachments, as #destroy will freeze
  # the attributes afterwards.
  base.before_destroy :initialize_remaining_attachments

  %w[validation save create update].each do |event|
    base.send("before_#{event}", "process_attachments_for_before_#{event}")
    base.send("after_#{event}", "process_attachments_for_after_#{event}")
  end
end

Instance Method Details

#attachment_reflection_for(name) ⇒ Object



76
77
78
# File 'lib/bulldog/has_attachment.rb', line 76

def attachment_reflection_for(name)
  self.class.attachment_reflections[name]
end

#destroy_attachmentsObject



54
55
56
57
58
# File 'lib/bulldog/has_attachment.rb', line 54

def destroy_attachments
  attachment_reflections.each do |name, reflection|
    _attachment_for(name).destroy
  end
end

#process_attachment(name, event, *args) ⇒ Object



70
71
72
73
74
# File 'lib/bulldog/has_attachment.rb', line 70

def process_attachment(name, event, *args)
  reflection = attachment_reflections[name] or
    raise ArgumentError, "no such attachment: #{name}"
  _attachment_for(name).process(event, *args)
end

#save_attachmentsObject



46
47
48
49
50
51
52
# File 'lib/bulldog/has_attachment.rb', line 46

def save_attachments
  attachment_reflections.each do |name, reflection|
    original_attachment = @original_attachments[name] and
      original_attachment.destroy
    _attachment_for(name).save
  end
end

#update_attachment_timestampsObject



60
61
62
63
64
65
66
67
68
# File 'lib/bulldog/has_attachment.rb', line 60

def update_attachment_timestamps
  attachment_reflections.each do |name, reflection|
    next unless send("#{name}_changed?")
    setter = "#{name}_updated_at="
    if respond_to?(setter)
      send(setter, Time.now)
    end
  end
end