Module: CarrierWave::Mongoid

Includes:
Mount
Defined in:
lib/carrierwave/orm/mongoid.rb

Instance Method Summary collapse

Methods included from Mount

#uploader_option, #uploader_options, #uploaders

Instance Method Details

#mount_uploader(column, uploader = nil, options = {}, &block) ⇒ Object

See CarrierWave::Mount#mount_uploader for documentation



12
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
67
68
69
70
71
72
73
# File 'lib/carrierwave/orm/mongoid.rb', line 12

def mount_uploader(column, uploader=nil, options={}, &block)
  options[:mount_on] ||= "#{column}_filename"
  field options[:mount_on]

  super

  alias_method :read_uploader, :read_attribute
  alias_method :write_uploader, :write_attribute

  include CarrierWave::Validations::ActiveModel

  validates_integrity_of  column if uploader_option(column.to_sym, :validate_integrity)
  validates_processing_of column if uploader_option(column.to_sym, :validate_processing)

  after_save      :"store_#{column}!"
  before_save     :"write_#{column}_identifier"
  after_destroy   :"remove_#{column}!"
  before_update   :"store_previous_model_for_#{column}"
  after_save      :"remove_previously_stored_#{column}"

  class_eval <<-RUBY, __FILE__, __LINE__+1
    def #{column}=(new_file)
      column = _mounter(:#{column}).serialization_column

      # Note (potatosalad): compatibility for mongoid < 2.1
      if self.respond_to?(:setup_modifications)
        # Note (Didier L.): equivalent of the <column>_will_change! ActiveModel method
        begin
          value = __send__(column)
          value = value.duplicable? ? value.clone : value
        rescue TypeError, NoMethodError
        end
        setup_modifications

        super.tap do
          @modifications[column] = [value, __send__(column)]
        end
      else
        # Note (potatosalad): compatibility for mongoid >= 2.1
        send(:"\#{column}_will_change!")
        super
      end
    end

    def #{column}_changed?
      column = _mounter(:#{column}).serialization_column
      send(:"\#{column}_changed?")
    end

    def find_previous_model_for_#{column}
      if self.embedded?
        ancestors       = [[ self.metadata.key, self._parent ]].tap { |x| x.unshift([ x.first.last.metadata.key, x.first.last._parent ]) while x.first.last.embedded? }
        reloaded_parent = ancestors.first.last.reload
        ancestors.inject(reloaded_parent) { |parent,(key,ancestor)| (parent.is_a?(Array) ? parent.find(ancestor.to_key.first) : parent).send(key) }.find(to_key.first)
      else
        self.class.find(to_key.first)
      end
    end

  RUBY

end