Friday, May 15, 2009

Flash, ActionScript, and Rails 2 Integration with SWFObject


I finished integrating our Flash Map into our Rails application. It was a bit tricky since I hadn't worked with ActionScript or Flash before, but in the end it all actually made sense.

The first thing I did was use SWFObject to embed the Flash Map (swf object) into my rails view. SWFObject is a javascript library that handles multi-browser support for flash. It really takes the heavy lifting out of implementing flash from the client side. I highly recommend downloading the js libraries (here).

In your view, simply include the js file:
<script type="text/javascript" src="/javascripts/swfobject.js"></script>

You can then display your flash object like this:
<script type="text/javascript">
flashVars["authenticity_token"] = AUTHENTICITY_TOKEN;
var flashParams = { menu: "false"};
var flashID = { id : "flashObject" };
swfobject.embedSWF("/path_to_file.swf", "flashObject", "550", "400",
"9.0.0", "expressInstall.swf", flashVars, flashParams, flashID);
</script>

That will display your Flash object in the DIV following the path_to_file.swf. So this will display the Flash object in the flashObject div in your page.

There are some important points to highlight. The flashVars contains variables you can pass to your ActionScript. This is important with rails because you NEED the authenticity token in the ActionScript so that your application can validate the request. You can certainly turn this off with a before_filter, but I do not advise it. The AUTHENTICITY_TOKEN is a parameter I set in my application.

If you want to use the before_filter to turn off login or authenticity validation, use this:

skip_before_filter :login_required, :check_new_user, :verify_authenticity_token

In our case, we also needed to pass flash variables to our ActionScript from the server. Without AJAX, your JS cannot get values from the server - because it's client side. In order to handle this, we used a rails "javascript_tag" to populate the flashVars with our values on the server side. You can do this like so:

<%= javascript_tag "var flashVars = { user_id: '#{@user.id}' };"%>

Or populate it with whatever variables you want.

In the ActionScript, you'll need to read in these parameters. You can do that like so:

userId = this.loaderInfo.parameters.user_id;

Of course, you'll have to pass the auth token back to the rails app as well. You can do that by appending the token to the URL:

http://your.url.com?authenticity_token="+authToken"

Just grab the auth token the same way you just grabbed the user_id.

Enjoy.

No comments: