Included Modules

Class Index [+]

Quicksearch

Ramaze::Helper::Upload

Helper module for handling file uploads. File uploads are mostly handled by Rack, but this helper adds some conveniance methods for handling and saving the uploaded files.

@example

  class MyController < Ramaze::Controller
    # Use upload helper
    helper :upload

    # This action will handle *all* uploaded files
    def handleupload1
      # Iterate over uploaded files and save them in the
      # '/uploads/myapp' directory
      get_uploaded_files.each_pair do |k, v|
        v.save(
          File.join('/uploads/myapp', v.filename),
          :allow_overwrite => true
        )

        if v.saved?
          Ramaze::Log.info(
            "Saved uploaded file named #{k} to #{v.path}."
          )
        else
          Ramaze::Log.warn("Failed to save file named #{k}.")
        end
      end
    end

    # This action will handle uploaded files beginning with 'up'
    def handleupload2
      # Iterate over uploaded files and save them in the
      # '/uploads/myapp' directory
      get_uploaded_files(/^up.*/).each_pair do |k, v|
        v.save(
          File.join('/uploads/myapp', v.filename),
          :allow_overwrite => true
        )

        if v.saved?
          Ramaze::Log.info(
            "Saved uploaded file named #{k} to #{v.path}."
          )
        else
          Ramaze::Log.warn("Failed to save file named #{k}.")
        end
      end
    end
  end

@author Lars Olsson @since 04-08-2011

Public Class Methods

included(mod) click to toggle source

Adds some class method to the controller whenever the helper is included.

     # File lib/ramaze/helper/upload.rb, line 173
173:       def self.included(mod)
174:         mod.extend(ClassMethods)
175:       end

Public Instance Methods

get_uploaded_files(pattern = nil) click to toggle source

This method will iterate through all request parameters and convert those parameters which represents uploaded files to Ramaze::Helper::Upload::UploadedFile objects. The matched parameters will then be removed from the request parameter hash.

Use this method if you want to decide whether to handle file uploads in your action at runtime. For automatic handling, use Ramaze::Helper::Upload::ClassMethods#handle_all_uploads or Ramaze::Helper::Upload::ClassMethods#handle_uploads_for instead.

@author Lars Olsson @since 04-08-2011 @param [Regexp] pattern If set, only those request parameters which

 has a name matching the Regexp will be checked for file uploads.

@return [Array] The uploaded files. @see Ramaze::Helper::Upload::ClassMethods#handle_all_uploads @see Ramaze::Helper::Upload::ClassMethods#handle_uploads_for

     # File lib/ramaze/helper/upload.rb, line 79
 79:       def get_uploaded_files(pattern = nil)
 80:         uploaded_files = {}
 81: 
 82:         # Iterate over all request parameters
 83:         request.params.each_pair do |k, v|
 84:           # If we use a pattern, check that it matches
 85:           if pattern.nil? or pattern =~ k
 86:             # Rack supports request parameters with either a single value or
 87:             # an array of values. To support both, we need to check if the
 88:             # current parameter is an array or not.
 89:             if v.is_a?(Array)
 90:               # Got an array. Iterate through it and check for uploaded files
 91:               file_indices = []
 92: 
 93:               v.each_with_index do |elem, idx|
 94:                 file_indices.push(idx) if is_uploaded_file?(elem)
 95:               end
 96: 
 97:               # Convert found uploaded files to
 98:               # Ramaze::Helper::Upload::UploadedFile objects
 99:               file_elems = []
100: 
101:               file_indices.each do |fi|
102:                 file_elems << Ramaze::Helper::Upload::UploadedFile.new(
103:                   v[fi][:filename],
104:                   v[fi][:type],
105:                   v[fi][:tempfile],
106:                   ancestral_trait[:upload_options] ||
107:                   Ramaze::Helper::Upload::ClassMethods.trait[
108:                     :default_upload_options
109:                   ]
110:                 )
111:               end
112: 
113:               # Remove uploaded files from current request param
114:               file_indices.reverse_each do |fi|
115:                 v.delete_at(fi)
116:               end
117: 
118:               # If the request parameter contained at least one file upload,
119:               # add upload(s) to the list of uploaded files
120:               uploaded_files[k] = file_elems unless file_elems.empty?
121: 
122:               # Delete parameter from request parameter array if it doesn't
123:               # contain any other elements.
124:               request.params.delete(k) if v.empty?
125:             else
126:               # Got a single value. Check if it is an uploaded file
127:               if is_uploaded_file?(v)
128:                 # The current parameter represents an uploaded file.
129:                 # Convert the parameter to a
130:                 # Ramaze::Helper::Upload::UploadedFile object
131:                 uploaded_files[k] = Ramaze::Helper::Upload::UploadedFile.new(
132:                   v[:filename],
133:                   v[:type],
134:                   v[:tempfile],
135:                   ancestral_trait[:upload_options] ||
136:                   Ramaze::Helper::Upload::ClassMethods.trait[
137:                     :default_upload_options
138:                   ]
139:                 )
140: 
141:                 # Delete parameter from request parameter array
142:                 request.params.delete(k)
143:               end
144:             end
145:           end
146:         end
147: 
148:         # If at least one file upload matched, override the uploaded_files
149:         # method with a singleton method that returns the list of uploaded
150:         # files. Doing things this way allows us to store the list of uploaded
151:         # files without using an instance variable.
152:         unless uploaded_files.empty?
153:           @_ramaze_uploaded_files = uploaded_files
154: 
155:           # Save uploaded files if autosave is set to true
156:           if ancestral_trait[:upload_options] and
157:              ancestral_trait[:upload_options][:autosave]
158:             uploaded_files().each_value do |uf|
159:               uf.save
160:             end
161:           end
162:         end
163: 
164:         # The () is required, otherwise the name would collide with the variable
165:         # "uploaded_files".
166:         return uploaded_files()
167:       end
uploaded_files() click to toggle source

Returns list of currently handled file uploads.

Both single and array parameters are supported. If you give your file upload fields the same name (for instance upload[]) Rack will merge them into a single parameter. The upload helper will keep this structure so that whenever the request parameter contains an array, the uploaded_files method will also return an array of Ramaze::Helper::Upload::UploadedFile objects for the same key.

@return [Hash] Currently uploaded files. The keys in the hash

 corresponds to the names of the request parameters that contained file
 uploads and the values consist of Ramaze::Helper::Upload::UploadedFile
 objects.
     # File lib/ramaze/helper/upload.rb, line 192
192:       def uploaded_files
193:         return @_ramaze_uploaded_files || {}
194:       end

Private Instance Methods

is_uploaded_file?(param) click to toggle source

Returns whether param is considered an uploaded file A parameter is considered to be an uploaded file if it is a hash and contains all parameters that Rack assigns to an uploaded file

@param [Hash] param A request parameter @return [Boolean]

     # File lib/ramaze/helper/upload.rb, line 205
205:       def is_uploaded_file?(param)
206:         if param.respond_to?(:has_key?)
207:           [:filename, :type, :name, :tempfile, :head].each do |k|
208:             return false if !param.has_key?(k)
209:           end
210: 
211:           return true
212:         else
213:           return false
214:         end
215:       end

Disabled; run with --debug to generate this.

[Validate]

Generated with the Darkfish Rdoc Generator 1.1.6.