Module: MongoidExt::Storage::ClassMethods

Defined in:
lib/mongoid_ext/storage.rb

Instance Method Summary collapse

Instance Method Details

#file_key(name, opts = {}) ⇒ Object



85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
# File 'lib/mongoid_ext/storage.rb', line 85

def file_key(name, opts = {})
  opts[:in] ||= :file_list

  define_method("#{name}=") do |file|
    if opts[:max_length] && file.respond_to?(:size) && file.size > opts[:max_length]
      errors.add(name, I18n.t("mongoid_ext.storage.errors.max_length", :default => "file is too long. max length is #{opts[:max_length]} bytes"))
    end

    if cb = opts[:validate]
      if cb.kind_of?(Symbol)
        send(opts[:validate], file)
      elsif cb.kind_of?(Proc)
        cb.call(file)
      end
    end

    if self.errors[name].blank?
      fl = send(opts[:in])

      if file.kind_of?(String)
        file = StringIO.new(file)
      end

      fl.get(name.to_s).put(name.to_s, file)
    else
      # we store the errors here because we want to validate before storing the file
      storage_errors.merge!(self.errors)
    end
  end

  define_method(name) do
    send(opts[:in]).get(name.to_s)
  end

  define_method("has_#{name}?") do
    send(opts[:in]).has_key?(name.to_s)
  end
end

#file_list(name) ⇒ Object



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
74
75
76
77
78
79
80
81
82
83
# File 'lib/mongoid_ext/storage.rb', line 47

def file_list(name)
  field name, :type => MongoidExt::FileList

  define_method(name) do
    varname = "@file_list_#{name}"

    return instance_variable_get(varname) if instance_variable_get(varname)

    list = self[name]

    if list.nil?
      list = self[name] = MongoidExt::FileList.new
    elsif list.kind_of?(::Hash)
      list = self[name] = MongoidExt::FileList.new(list)
    end

    list.parent_document = self
    list.list_name = name

    instance_variable_set(varname, list)
    list
  end

  set_callback(:create, :after) do |doc|
    l = doc.send(name)
    l.sync_files

    query = doc._updates
    if !query.blank?
      doc.collection.find(:_id => doc.id).update(query, {:multi => true})
    end
  end

  set_callback(:destroy, :before) do |doc|
    doc.send(name).destroy_files
  end
end

#gridfsObject



43
44
45
# File 'lib/mongoid_ext/storage.rb', line 43

def gridfs
  @gridfs ||= Mongoid::GridFS
end