Rails on the Run

Rails experiments by Matt Aimonetti

Browsing Posts tagged flash

I recently had to deal with an interesting challenge. I had to write a simple interface between a rails app and a Flash application. Nothing hard and if you browse the archives, you’ll find examples and tutorials on how to create a REST interface to communicate between Rails and Flash.

The thing was that this time I had to interface with a model using attachmentfu. I’m a great fan of afu and it’s definitely the best way of dealing with uploads.

My model looked more or less like that:

class Photo < ActiveRecord::Base

belongs_to :user

    :content_type => :image,
    :storage => :file_system,
    :max_size => 10.megabytes,
    :resize_to => '640x480>',
    :thumbnails => { :thumb => '100x100>',
                              :preview => '300x200>',
  # read more about validates_existence_of http://blog.hasmanythrough.com/2007/7/14/validate-your-existence
  validates_existence_of :user

My show action in my photo controller could have looked a bit like that:

respond_to do |format|
  format.html # show.html.erb
  format.xml  { render :x ml => @photo }

That’s great, the problem is that we are displaying a lot of information that our Flash client doesn’t need to see, actually we are exposing a lot of information nobody should ever see and we are not displaying what we should. On top of being a waste of bandwidth and giving too much work to the client, we are not actually providing the user with the details of the thumbnail.

The first thing to do would be not to display some of the object attributes, the to_xml method lets you do that.

Note that in Edge, Rails will automatically try to convert your object using toxml, you don’t even need to mention it. However in our case, we want to use some _advanced features offered by to_xml, and here is how our code should look like:

format.xml do
  render :x ml => @photo.to_xml( :except => [ :id, :filename, :updated_at, :user_id, :height, :width], :skip_types => true )

What I just did is very simple, we rendered our object as an xml object but we didn’t convert few attributes, :id, :filename, :updatedat, :userid, :height, :width. By default Rails also adds the object type, we don’t really need that right now, so let’s skip them.

(The reason why I don’t want to convert the filename is that I want to provide our Flash client with the photo thumbnail instead of the original picture.)

As far as I know, to_xml doesn’t let you create new attributes. (if I have some time, I’ll submit a patch to get that added).

What we are trying to do is to display the avatar of a user. We found the photo record using @user.photo but that’s the original photo and we want to provide Flash with the avatar info, not the original.

What we need to do is to simply add a new attribute called avatar:

format.xml do
  @photo[:avatar] = @photo.public_filename(:thumb)
  render :x ml => @photo.to_xml( :except => [ :id, :filename, :updated_at, :user_id, :height, :width], :skip_types => true )

Simple enough, but it took me a little while to figure it out ;)

Voila, we now have a clean, trimmed and safe XML returned object that you can be consumed by our Flash client. Ohh, and we added a new attribute that the original object didn’t have :)

mimetype_fu/ is a new plugin I just wrote. It’s simple and it can be really useful if you need to get the mime type of a file already on your server.

During one of my project, I add to migrate old assets from a legacy system to a new Rails app. The new app uses attachment fu and even though techno weenie did an amazing job, attachmentfu validation is based on the content type. Afu gets the content type coming from the CGI query.

Unit test has a helper faking this process but in real life, if you use a Flash uploader (Flash doesn’t give you the proper mime type/content type) or if you want to migrate files, the attachment_fu validation won’t work for you.

The solution is simple: mimetype_fu/

mimetype_fu/ extends the File class and is really easy to use:


Check it out http://code.google.com/p/mimetype-fu/

Expect a post showing how a ninja would use the mimetypefu / attachmentfu combo :)

In part I I explained how to access Rails data from Flash.

However Yves aka Kadoudal was wondering what I did with Rails to return the event record:

Rails.get(‘events’, rails_events); how rails returns the event record as we don’t call a controller/action … ? I believe doing it RESTFul it’s depending upon your route ? is it not?

We are actually calling a controller/action If you look at the Restfulflash class, you’ll notice a function called get

public function get(controller, callback){
        var railsReply:XML = new XML();
        railsReply.ignoreWhite = true;
        railsReply.onLoad = function(success:Boolean){
            if (success) {
                    trace ('Rails responded: '+railsReply);
                    callback.text = railsReply;
            } else {
                    trace ('Error while waiting for Rails to reply');
               callback.text = 'error';
        var railsRequest:XML = new XML();
        railsRequest.sendAndLoad(this.gateway+controller, railsReply);
        delete railsRequest;

What’s really interesting are the following 2 lines:

railsRequest.sendAndLoad(this.gateway+controller, railsReply);

I’m preparing a request that I will send to my gateway mentioning the controller name. In the previous example I was calling the ‘events’ controller: http://mysite.fr/events because I’m using REST and because my request is a ‘get’ Rails will call the index action.

for more info on RESTful design check the nice series available from the softies on rails blog

Let’s just look at my code and see what’s up with rails magic :)

Here is my index action sending you back a different object based on the header of your request.

class EventsController < ApplicationController
  # GET /events
  # GET /events.xml
  def index
    @events = Event.find(:all)

    respond_to do |format|
      format.html # index.rhtml
      format.xml  { render :x ml => @events.to_xml }
      format.json { render :json => @events.to_json }

That’s it, and it was automatically created for you by the script/generate scaffold_resource command :)

Since I’m answering Yves’ questions, let’s look at his final question:

problem : what if the xml returned is not a record, but it has to be prepared by Rails…
I explain, right now my rails view .. I have a javascript object passing all the info via JS
I would like to replace the datasource file by a direct call to rails from Flash, so this param will disappear… so (correct me if I am wrong)
1- I need to pass a user_id value in JS to Flash in the script…
2- Flash need to send a request to Rails (controller/action/id to prepare the xml… ) to get in return a correct xlm object to be displayed

1- I’m not sure why you need to pass the user_id from JS to Flash but I guess Flash doesn’t know what user to query?? (anyway that would work)

2- If you are using REST, Flash just needs make a get call to /controller/id Make sure to set the request header type as xml, like I did in my function railsRequest.contentType=”application/xml”; Otherwise I believe (but didn’t try) that you can call /events/1.xml where 1 id the id of the event you want to retrieve.

By the way, it will call the show action from the events controller which looks like that:

def show
  @event = Event.find(params[:id])

  respond_to do |format|
    format.html # show.rhtml
    format.xml  { render :x ml => @event.to_xml }