Sha256: 4403dc8871edd7427e0774ce2bce90bec8305c8a4af633cd2833d1ecca8c5f2a

Contents?: true

Size: 1.88 KB

Versions: 7

Compression:

Stored size: 1.88 KB

Contents

module InstantUpload
  module Helpers

    module ControllerHelper
      extend ActiveSupport::Concern

      included do
        helper_method :handle_upload, :load_uploaded_files, :clear_uploaded_files
      end

      def handle_upload(record, field, options ={})
        sesssion_key = "#{record.class.name.downcase}_#{field}"

        if request.env['HTTP_X_INSTANT_UPLOAD']
          if options[:multi].present? # multiple
            files = []

            record.send(field).each do |img|
              file = InstantUpload::Upload.new
              file.file = img.path
              file.save
              files << file
            end

            session[sesssion_key] = [] if session[sesssion_key].blank?
            session[sesssion_key] << files.map { |f| f.id }

            render json: record.send(field)
          else
            file = InstantUpload::Upload.new
            file.file = record.send(field)
            file.save

            session[sesssion_key] = file.id

            render json: record
          end

          return true
        else
          load_uploaded_files(record, field, options)
        end

        false
      end

      def load_uploaded_files(record, field, options ={})
        sesssion_key = "#{record.class.name.downcase}_#{field}"

        if session[sesssion_key].present?
          if options[:multi].present? # multiple
            files = InstantUpload::Upload.find(session[sesssion_key])
            record.send(field).clear

            files.each do |f|
              record.send(field).build(options[:multi] => f.file)
            end
          else # single
            file = InstantUpload::Upload.find(session[sesssion_key])
            record.send("#{field}=", file.file)
          end
        end
      end

      def clear_uploaded_files(record, field)
        session.delete("#{record.class.name.downcase}_#{field}")
      end

    end

  end
end

Version data entries

7 entries across 7 versions & 1 rubygems

Version Path
instant-upload-1.0.6 lib/instant_upload/helpers/controller_helper.rb
instant-upload-1.0.5 lib/instant_upload/helpers/controller_helper.rb
instant-upload-1.0.4 lib/instant_upload/helpers/controller_helper.rb
instant-upload-1.0.3 lib/instant_upload/helpers/controller_helper.rb
instant-upload-1.0.2 lib/instant_upload/helpers/controller_helper.rb
instant-upload-1.0.1 lib/instant_upload/helpers/controller_helper.rb
instant-upload-1.0.0 lib/instant_upload/helpers/controller_helper.rb