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



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

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



74
75
76
# File 'lib/bulldog/has_attachment.rb', line 74

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

#destroy_attachmentsObject



52
53
54
55
56
# File 'lib/bulldog/has_attachment.rb', line 52

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

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



68
69
70
71
72
# File 'lib/bulldog/has_attachment.rb', line 68

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



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

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



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

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