Module: Ramaze::Helper::Upload

### Home Classes Methods

### In Files

- lib/ramaze/helper/upload.rb

### Namespace

- MODULE Ramaze::Helper::Upload::ClassMethods
- CLASS Ramaze::Helper::Upload::UploadedFile

### Methods

- ::included
- #get_uploaded_files
- #uploaded_files

### Included Modules

- Ramaze::Traited

### Files

- Gemfile
- Rakefile

### Class/Module Index

Quicksearch

- Ramaze
- Ramaze::App
- Ramaze::Bin
- Ramaze::Bin::Create
- Ramaze::Bin::Runner
- Ramaze::Cache
- Ramaze::Cache::LRU
- Ramaze::Cache::LocalMemCache
- Ramaze::Cache::MemCache
- Ramaze::Cache::Redis
- Ramaze::Cache::Sequel
- Ramaze::Controller
- Ramaze::CoreExtensions
- Ramaze::CoreExtensions::Object
- Ramaze::CoreExtensions::String
- Ramaze::Current
- Ramaze::DefaultController
- Ramaze::Files
- Ramaze::Gestalt
- Ramaze::Helper
- Ramaze::Helper::Auth
- Ramaze::Helper::Bench
- Ramaze::Helper::BlueForm
- Ramaze::Helper::BlueForm::Form
- Ramaze::Helper::CSRF
- Ramaze::Helper::Cache
- Ramaze::Helper::Cache::SingletonMethods
- Ramaze::Helper::Email
- Ramaze::Helper::Erector
- Ramaze::Helper::Flash
- Ramaze::Helper::Formatting
- Ramaze::Helper::Gestalt
- Ramaze::Helper::Gravatar
- Ramaze::Helper::Identity
- Ramaze::Helper::Layout
- Ramaze::Helper::Layout::SingletonMethods
- Ramaze::Helper::Link
- Ramaze::Helper::Localize
- Ramaze::Helper::Localize::Dictionary
- Ramaze::Helper::Localize::Parser
- Ramaze::Helper::Markaby
- Ramaze::Helper::Maruku
- Ramaze::Helper::Paginate
- Ramaze::Helper::Paginate::Paginator
- Ramaze::Helper::Paginate::Paginator::ArrayPager
- Ramaze::Helper::Paginate::Paginator::DataMapperPager
- Ramaze::Helper::Remarkably
- Ramaze::Helper::RequestAccessor
- Ramaze::Helper::SendFile
- Ramaze::Helper::SimpleCaptcha
- Ramaze::Helper::Stack
- Ramaze::Helper::Thread
- Ramaze::Helper::Upload
- Ramaze::Helper::Upload::ClassMethods
- Ramaze::Helper::Upload::UploadedFile
- Ramaze::Helper::UserHelper
- Ramaze::Helper::UserHelper::Wrapper
- Ramaze::Helper::XHTML
- Ramaze::LRUHash
- Ramaze::Logger
- Ramaze::Logger::Informer
- Ramaze::Logger::LogHub
- Ramaze::Logger::Logger
- Ramaze::Logger::RotatingInformer
- Ramaze::Logger::Syslog
- Ramaze::Logging
- Ramaze::Reloader
- Ramaze::Reloader::Hooks
- Ramaze::Reloader::WatchInotify
- Ramaze::Reloader::WatchStat
- Ramaze::Request
- Ramaze::Response
- Ramaze::SpecLogger
- Ramaze::View
- Ramaze::View::Erector
- Ramaze::View::Erubis
- Ramaze::View::Ezamar
- Ramaze::View::Gestalt
- Ramaze::View::Haml
- Ramaze::View::Liquid
- Ramaze::View::Liquid::Tag
- Ramaze::View::Lokar
- Ramaze::View::Mustache
- Ramaze::View::Mustache::RamazeContext
- Ramaze::View::Nagoro
- Ramaze::View::Remarkably
- Ramaze::View::Sass
- Ramaze::View::Slippers
- Ramaze::View::Tagz
- Ramaze::View::Tagz::Methods
- Ramaze::View::Tenjin
- Innate
- Innate::View
- Innate::View::Slim
- Nagoro
- Nagoro::Pipe
- Nagoro::Pipe::RenderPartial
- Bacon
- Bacon::PrettyOutput
- Erector
- Erector::Widget
- Rack
- Rack::RouteExceptions
- Tenjin
- Tenjin::Template
- BlankSlate
- Controller
- MainController
- Object

No matching classes.

# 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
    def self.included(mod)
      mod.extend(ClassMethods)
    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
    def get_uploaded_files(pattern = nil)
      uploaded_files = {}

      # Iterate over all request parameters
      request.params.each_pair do |k, v|
        # If we use a pattern, check that it matches
        if pattern.nil? or pattern =~ k
          # Rack supports request parameters with either a single value or
          # an array of values. To support both, we need to check if the
          # current parameter is an array or not.
          if v.is_a?(Array)
            # Got an array. Iterate through it and check for uploaded files
            file_indices = []

            v.each_with_index do |elem, idx|
              file_indices.push(idx) if is_uploaded_file?(elem)
            end

            # Convert found uploaded files to
            # Ramaze::Helper::Upload::UploadedFile objects
            file_elems = []

            file_indices.each do |fi|
              file_elems << Ramaze::Helper::Upload::UploadedFile.new(
                v[fi][:filename],
                v[fi][:type],
                v[fi][:tempfile],
                ancestral_trait[:upload_options] ||
                Ramaze::Helper::Upload::ClassMethods.trait[
                  :default_upload_options
                ]
              )
            end

            # Remove uploaded files from current request param
            file_indices.reverse_each do |fi|
              v.delete_at(fi)
            end

            # If the request parameter contained at least one file upload,
            # add upload(s) to the list of uploaded files
            uploaded_files[k] = file_elems unless file_elems.empty?

            # Delete parameter from request parameter array if it doesn't
            # contain any other elements.
            request.params.delete(k) if v.empty?
          else
            # Got a single value. Check if it is an uploaded file
            if is_uploaded_file?(v)
              # The current parameter represents an uploaded file.
              # Convert the parameter to a
              # Ramaze::Helper::Upload::UploadedFile object
              uploaded_files[k] = Ramaze::Helper::Upload::UploadedFile.new(
                v[:filename],
                v[:type],
                v[:tempfile],
                ancestral_trait[:upload_options] ||
                Ramaze::Helper::Upload::ClassMethods.trait[
                  :default_upload_options
                ]
              )

              # Delete parameter from request parameter array
              request.params.delete(k)
            end
          end
        end
      end

      # If at least one file upload matched, override the uploaded_files
      # method with a singleton method that returns the list of uploaded
      # files. Doing things this way allows us to store the list of uploaded
      # files without using an instance variable.
      unless uploaded_files.empty?
        @_ramaze_uploaded_files = uploaded_files

        # Save uploaded files if autosave is set to true
        if ancestral_trait[:upload_options] and
           ancestral_trait[:upload_options][:autosave]
          uploaded_files().each_value do |uf|
            uf.save
          end
        end
      end

      # The () is required, otherwise the name would collide with the variable
      # "uploaded_files".
      return uploaded_files()
    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
    def uploaded_files
      return @_ramaze_uploaded_files || {}
    end

[Validate]

Generated with the Darkfish Rdoc Generator 2.