Justin Weidmann Everything Ruby http://justinweidmann.com/ http://justinweidmann.com/ 2009-01-04T11:59:22-06:00 2009-01-04T11:59:22-06:00 Getting up and running with SWFUpload on Merb and jQuery http://justinweidmann.com/2009/1/4/getting-up-and-running-with-swfupload-on-merb-and-jquery SWFUpload is a great javascript kit for adding nice, multiple file uploads to your application. Today were going to go through the steps to get SWFUpload working with Merb 1.x. All this code is valid for SWFUpload v 2.2.0, which you can download here.


Generate your new merb app

      merb-gen app picture_place


Create the picture resource
We will need a picture model to store our pictures, so lets create that now.

      merb-gen resource picture


Install dm-paperclip
Paperclip is a great gem for handling picture uploads. Open up /config/dependencies.rb and add the following

      dependency "dm-paperclip"


Setup the picture model
Add the following to /app/models/picture.rb

      include Paperclip::Resource
      has_attached_file :image,
        :default_url => "/uploads/pictures/:attachment/missing_:style.png",
        :url => "/uploads/pictures/:id/:style/:basename.:extension",
        :path => ":merb_root/public/uploads/pictures/:id/:style/:basename.:extension",
        :styles => {:small => "55x55#", :medium => "100x100#", :large => "600x600>" }
The has_attached_file method is where you setup paperclip options. :default_url is the image to show if paperclip can't find the requested image. :url is the place where your images get stored. :path is the path the image is served from. :styles creates thumbnails out of your picture, you can define custom sizes here. The has_attached_file method will also add all the columns to the database that are needed such as content-type, filename etc.



Setup the router
Were going to want to use an action in the picture controller called 'swf_upload' to handle uploads coming from SWFUpload, so lets set that up in the router.

      with(:controller => "pictures") do
        match('/pictures/swf_upload').to(:action => "swf_upload").fixatable
      end
Notice the .fixatable on the end of the match method, this is important for passing session info through flash and back again.



Setup the controller
Open up your pictures controller and add the following.

      def swf_upload
        only_provides :html
        @picture = Picture.new
        @picture.image = params[:Filedata]
        ## If the picture belongs to a user, uncomment this line
        ## @picture.user_id = session.user.id
        if @picture.save
          return "success"
        else
          return ""
        end
      end
This is the basic method for handling your uploads. @picture.image = params[:Filedata] is what sets up all the info about the picture for the database.



Get the necessary files
We are going to need a few javascript files to SWFUpload, so were gonna grab those now. First create a new directory in public/ called swfupload. Then head over here, download all the files and put them in public/swfupload/


Now onto the view
Now for the fun stuff. Open up /app/views/pictures/new.html.haml and add the following

      %script{:type => "text/javascript", :src => "/swfupload/swfupload.js"}
      %script{:type => "text/javascript", :src => "/swfupload/swfupload.queue.js"}
      %script{:type => "text/javascript", :src => "/swfupload/fileprogress.js"}
      %script{:type => "text/javascript", :src => "/swfupload/handlers.js"}
      
      :javascript
        var swfu;
        $(document).ready(function(){
          var settings = {
            upload_url: "/pictures/swf_upload?_picture_place_session_id=#{cookies[:_picture_place_session_id]}",
            flash_url: "/swfupload/swfupload.swf",
            file_size_limit: "10485760", // 10 MB
            file_types: "*.jpg;*.png;*.gif",
            file_types_description: "JPG, GIF, or PNG Image Files",
            file_upload_limit : 100,
            file_queue_limit : 0,
            debug: false,
            custom_settings : {
              progressTarget : "images"
            },
            // Button settings
            button_width: "200",
            button_height: "32",
            button_placeholder_id: "browse",
            button_text: '<span class="theFont">Select files to upload</span>',
            button_text_style: ".theFont { font-size: 16; font-family: arial; }",
            // Handlers
            file_queued_handler : fileQueued,
            file_dialog_complete_handler: fileDialogComplete,
            upload_start_handler: uploadStart,
            upload_progress_handler: uploadProgress,
            upload_error_handler: uploadError,
            upload_success_handler: uploadSuccess,
            upload_complete_handler: uploadComplete
          };
          swfu = new SWFUpload(settings);
          // Add Event Handlers
          $('#browse').click(function() { swfu.selectFiles(); });
          $('#upload').click(function() { swfu.startUpload(); });
        });
      
      %h1 Upload some new pictures
      #upload-actions
        #browse Select Files
        %a.upload-button#upload{:href => '#', 'onclick' => 'return false'} Upload files
      #images
So whats going on here? The first two lines include the javascript files we need. Most of the settings are self explanatory, but note the upload_url line, were passing the users session key through so that we know which user uploaded the picture in the swf_upload action. This will give us a basic working upload form, go ahead and fire up merb and give it a shot.



Give it a test run
We now have working uploads, fire up your browser and head to http://localhost:4000/pictures/new and try uploading some pictures. I have a sample app made up on github you can check also look at.

]]>
2009-01-04T11:59:22-06:00
Making Merb 1.0 RC1 Play Nice With Passenger http://justinweidmann.com/2008/10/15/making-merb-1-0-rc1-play-nice-with-passenger MerbCamp wrapped up last weekend, and we were given Merb 1.0 RC1 . So I dove right in and upgraded a couple apps from 0.9.8, and everything was fine until I deployed the apps in production under Passenger . The first thing is merb now comes with a public/.htaccess file, and there are a couple lines we need to comment out in here so that Passenger doesn't use fcgi. Make sure the following lines are commented out in your public/.htaccess file

      #RewriteRule ^(.*)$ merb.fcgi [QSA,L]

There is no need for fcgi behind Passenger since Passenger uses rack. Now you should be able to deploy your app behind Passenger without many problems. There is still one problem you may come across. For some reason you can't have local variables set in a controller or your app will fail with the following error message

      /usr/local/lib/rubyEE/lib/ruby/gems/1.8/gems/ParseTree-2.2.0/lib/parse_tree.rb:151: 
      [BUG] Segmentation fault

So instead of this

      def show
        @post = Post.get(params[:id])
        number = 100
        number = number + 100
      end

You would need to do this

      def show
        @post = Post.get(params[:id])
        @number = 100
        @number = @number + 100
      end

I have not yet figured out why local variables cause the segmentation fault, but this is a quick way to get around it so that you app will still work.

]]>
2008-10-15T12:58:54-06:00
You might be a web designer if... http://justinweidmann.com/2008/10/9/you-might-be-a-web-designer-if- Canadian Developer Connection they have a great list of 'you might be a web designer if' posted up. Just a couple of my favorites...

1. If you overuse AJAX for household chores, you might be a Web developer.
2. If you think "passing the Acid test" doesn't refer to a drug problem, you might be a Web developer.
3. If your "Yo Mamma" jokes include the phrase, "padding: 200%", you might be a Web developer.

Do you have some of your own that aren't on the list? Lets hear them in the comments.]]>
2008-10-09T10:29:20-06:00
Welcome to Justin Weidmann.com http://justinweidmann.com/2008/7/10/welcome-to-justin-weidmann-com 2008-07-10T11:49:13-06:00