Rails on the Run

Rails experiments by Matt Aimonetti

Browsing Posts tagged REST

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.contentType='application/xml';
        railsRequest.sendAndLoad(this.gateway+controller, railsReply);
        delete railsRequest;
    }

What’s really interesting are the following 2 lines:

railsRequest.contentType=”application/xml”;
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 }
    end
  end

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 }
  end
end

With the recent Buzz around Adobe Apollo I figured out that since I recently switched to Mac and that I didn’t try the latest Flex upgrade, I should try Flex 2.01 for Mac.

I really like what Adobe did with Flex, Unit testing, better accessibility, etc… but one thing I regret, it’s getting closer and closer to Java and AS3 syntax is a pain to use when you got used to Ruby.

Anyway, what I really wanted to do was to have Flash quickly access my Restful Rails app. The adobe guys came up with a RoR Ria SDK but well…. it only covers Flex and requires FlashPlayer 9.
I also found some great tutorials on how to use the efficient AMF messaging protocol with Rails using the WebOrb for Rails plugins

All that was really nice and I had fun, but it was an overkill for what I wanted to do. Let me show you how in less than 5 minutes how you can access you Rails Model from Flash and add some new item directly from Flash.

Create your new Rails app and use the script/generate scaffold_resource command to generate your Event Model.

script/generate scaffold_resource Event

It should create all that for you:

exists  app/models/
  exists  app/controllers/
  exists  app/helpers/
  create  app/views/events
  exists  test/functional/
  exists  test/unit/
  create  app/views/events/index.rhtml
  create  app/views/events/show.rhtml
  create  app/views/events/new.rhtml
  create  app/views/events/edit.rhtml
  create  app/views/layouts/events.rhtml
  identical  public/stylesheets/scaffold.css
  create  app/models/event.rb
  create  app/controllers/events_controller.rb
  create  test/functional/events_controller_test.rb
  create  app/helpers/events_helper.rb
  create  test/unit/event_test.rb
  create  test/fixtures/events.yml
  exists  db/migrate
  create  db/migrate/001_create_events.rb
  route  map.resources :events

let’s edit the migration file:
db/migrate/001createevents.rb

class CreateEvents < ActiveRecord::Migration
  def self.up
    create_table :events do |t|
      t.column :title, :string
      t.column :description, :string
      t.column :location, :string
        t.column :starts_at, :datetime
        t.column :ends_at, :datetime
    end
  end

  def self.down
    drop_table :events
  end
end

And let’s add some fixtures:
test/fixtures/events.yml

meeting:
  id: 1
  title: Meeting
  description: Boring meeting with the whole staff
  location: conference room
  starts_at: 2007-11-02 09:00:00
  ends_at: 2007-11-02 10:30:00
Joe_bday:
  id: 2
  title: Joe Bday Party
  description: Come and celebrate Joe's Birthday
  location: Lapin Agile Pub
  starts_at: 2007-09-07 20:00:00
  ends_at: 2007-09-07 23:30:00

Ok, now simply migrate your database,load the fixtures and start the webrick:

rake db:migrate
rake db:fixtures:load
script/server

Great, we are done with Rails.

Let’s launch Flash

Create a new Flash document and create a new .As fie in TextMate (or your favorite editor). We’ll write a quick ActionScript class to access Rails.

class Restfulflash{
    public var gateway:String;

    function Resftfulflash(gateway:String){
        this.set_gateway(gateway);
    }
    public function set_gateway(gateway:String){
        this.gateway = gateway;
        trace("gateway set to:"+gateway);
    }

    public function get(model, 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.contentType="application/xml";
        railsRequest.sendAndLoad(this.gateway+model, railsReply);
        delete railsRequest;
    }

    public function create(model, newItem){
        railsRequest.onLoad = function(success){
                trace("Item creation success: " + success);
                trace(this);
        };
        var railsRequest:XML = new XML();
        railsRequest.parseXML(newItem);
        railsRequest.contentType="application/xml";
        railsRequest.sendAndLoad(this.gateway+model+'/create/index.html', railsRequest,'POST');
        delete railsRequest;
    }
}

Save this file in the same directory as your .fla file

In your fla file add:

// Create a XML object to hold the events from our Rails app
rails_events = new XML();

// Prepare the connection to Rails (it would be nicer to do that in 1 step, but to make things clearer i decided to do it in 2)
var rails:Restfulflash = new Restfulflash();
rails.set_gateway("http://localhost:3000/");

// Get the events from rails and load the result in the rails_event XML object.
rails.get('events', rails_events);
trace(rails_events);

// Let's create a new event
newEvent = new XML('<event><description>Spend some time with Grandma before its too late</description><ends-at type="datetime">2007-11-02T18:30:00-07:00</ends-at><id type="integer">1</id><location>Paris, France</location><starts-at type="datetime">2007-11-02T16:00:00-07:00</starts-at><title>Visit Grandma</title></event>&#8217;)
rails.create(&#8216;events&#8217;, newEvent);

// Verify  that the event was added
rails.get(&#8216;events&#8217;, rails_events);
trace(rails_events);

There you go, you have all the events provided to you by Rails nicely prepared in an easy to parse XML object. You can bind the results to a Datagrid or display the info the way you want it. Ohh and by the way, we just added a new Event to the database… easy, isn’t it? The code is a bit dirty but it’s still a good example why you need to use REST and how easy it is to get Flash to talk with Rails. (I strongly encourage that you also look at the very good WebOrb plugin for Rails)