Home > Articles > Programming > Ruby

  • Print
  • + Share This
This chapter is from the book

Accessing our RESTful Application with Flex

In this section, you will build a simple Flex application that will enable a user to create and maintain accounts, to buy and sell stock for those accounts, and to view the movements of a given stock. The application will look like what is shown in Figure 3.1.

Figure 3.1 The application interface

The application has three grids. The ones for Accounts and Positions are editable, so they can be used to directly update the name of an account or to enter the stock ticker and quantity to buy. Let’s create the application in three steps: first the accounts part, then the positions, and finally, the movements.

Accounts

Accessing a RESTful Rails resource from Flex consists of creating one HTTPService component for each of the actions the resource supports. For the account resource, the Rails application exposes the four URLs shown in Table 3.5.

Table 3.5  The four URLs Exposed by the Rails App for the Account Resource

Action

Verb

Url

index
GET
/accounts
create
POST
/accounts
update
PUT
/accounts/:id
delete
DELETE
/accounts/:id

Before we create the service components, let’s declare a bindable variable to hold the data the server returns.

[Bindable] private var accounts:XML;

And let’s declare the data grid that will display this list of accounts.

<mx:DataGrid  id="accountsGrid"      
    dataProvider="{accounts.account}"
    editable="true">
  <mx:columns>
    <mx:DataGridColumn headerText="Id" dataField="id" editable="false"/>
    <mx:DataGridColumn headerText="Name" dataField="name" />
  </mx:columns>
</mx:DataGrid>  

We make the grid editable except for the first id column. We will use this later when adding the create and update functionality. Note also that we set the dataProvider to accounts.account. The accounts variable will contain the following XML, as returned by the Rails accounts controller index action:

<?xml version="1.0" encoding="UTF-8"?>
<accounts type="array">
  <account>
    <created-at type="datetime">2008-06-13T13:56:04Z</created-at>
    <id type="integer">1</id>
    <name>daniel</name>
    <updated-at type="datetime">2008-06-13T13:56:04Z</updated-at>
  </account>
  <account>
    <created-at type="datetime">2008-06-13T14:01:41Z</created-at>
    <id type="integer">2</id>
    <name>tony</name>
    <updated-at type="datetime">2008-06-14T02:19:46Z</updated-at>
  </account>
</accounts>  

And specifying accounts.account as the data provider of the grid returns an XMLList containing all the specific accounts that can be loaded directly in the data grid and referred to directly in the data grid columns. The first column will display the IDs of the accounts and the second column the names.

Before declaring all our services we can define the following constant in ActionScript to be used as the root context for all the urls.

    private const CONTEXT_URL:String = "http://localhost:3000";

To retrieve the account list, we need to declare the following index service:

<mx:HTTPService id="accountsIndex" url="{CONTEXT_URL}/accounts" 
    resultFormat="e4x" 
    result="accounts=event.result as XML"/>

In the result handler, we assign the result to the accounts variable we declared above. Again, we need to specify the resultFormat on the HTTPService instance, which in the case of "e4x" ensures that the returned XML string is transformed to an XML object.

Next we can declare the create service, as follows.

<mx:HTTPService id="accountsCreate"  url="{CONTEXT_URL}/accounts"
    method="POST" resultFormat="e4x" contentType="application/xml"
    result="accountsIndex.send()"  />

We set the HTTP verb using the method attribute of the HTTPService component to match the verb Rails expects for this operation. We also need to set the contentType to "application/xml" to enable us to pass XML data to the send method and to let Rails know that this is an XML-formatted request. Also notice that we issue an index request in the result handler. This request enables a reload of the account list with the latest account information upon a successful create, and thus, by reloading the data in the grid, we would now have the ID of the account that was just created.

For the update service, we need to include in the URL which account ID to update. We use the grid-selected item to get that ID. Since the name column is editable, you can click in the grid, change the name, and press the update button (which we will code shortly). Also note that, in this case, we don’t reload the index list because we already have the ID and the new name in the list.

<mx:HTTPService id="accountsUpdate"
 url="{CONTEXT_URL}/accounts/{accountsGrid.selectedItem.id}?_method=put"
    method="POST" resultFormat="e4x"  contentType="application/xml"  />

As explained in the previous chapter, the Flash Player doesn’t support either the delete or put verbs, but Rails can instead take an additional request parameter named _method. Also note that we reload the account list after a successful delete request, which provides the effect of removing the account from the list. We could have simply removed the account from the account list without doing a server round trip.

<mx:HTTPService id="accountsDelete"  
    url="{CONTEXT_URL}/accounts/{accountsGrid.selectedItem.id}"
    method="POST" resultFormat="e4x" contentType="application/xml"
    result="accountsIndex.send()" >
  <mx:request>
    <_method>delete</_method>
  </mx:request>  
</mx:HTTPService>

When the Flex application starts, we want to automatically load the account list. Implement this by adding the applicationComplete handler to the application declaration, and issue the send request to the account index service.

<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="vertical"
  applicationComplete="accountsIndex.send()">    

Now when your application starts, the account index request is made to the server, and the result is assigned to the accounts variable, which is bindable, meaning the grid reloads automatically when the assignment occurs. Next we’ll add the create, update, and delete functionality for the account list.

What we don’t show in these examples is the overall layout of the application. But, in short, we have a horizontal divide box that contains three panels, one for each resource:

<mx:HDividedBox> 
  <mx:Panel title="Accounts" />
  <mx:Panel title="Positions" />
  <mx:Panel title="Movements" />
</mx:HDividedBox>              

Each panel contains the grid and a control bar that has several buttons for the accounts and positions panels:

<mx:Panel>
  <mx:DataGrid />
   <mx:ControlBar>
      <mx:Button />
      <mx:Button />
   </mx:ControlBar>
</mx:Panel>  

More frequently than using an editable data grid, your application may have data entry forms that show the detail of the selected record or a new entry form when adding data. This is also how a typical Rails application generates HTML. In our example, we are using the editable grid to achieve the same functionality, but in the end, which approach you use will depend on your application requirements.

To add a new account, we need the New button.

<mx:Button label="New" 
  click="addNewAccount()" 
  enabled="{accountsGrid.dataProvider!=null}" />

This button invokes the addNewAccount method, which simply adds a new XML node to the XML accounts list. There is no server call happening yet.

private function addNewAccount():void {
  accounts.appendChild(<account><id></id><name>new name</name></account>);
}

The user can then change the name of the account directly in the grid and use the following Create button to send the new account information to the Rails application:

<mx:Button 
  label="{accountsGrid.selectedItem.id==''?'Create':'Update'}" 
  click="accountsGrid.selectedItem.id=='' ? 
          accountsCreate.send(accountsGrid.selectedItem) :
          accountsUpdate.send(accountsGrid.selectedItem)" />

If the selected item has no ID, it’s a new record and the label of the button is set to Create, and the click action triggers the accountsCreate service. If an ID exists, the button transforms into an Update button, which uses the accountsUpdate service. Now we just need to add the delete functionality. If the selected item has an ID, in other words, if it exists on the server, the click handler invokes the accountsDelete service, which deletes the current record. We also support the scenario where you click the new button but want to cancel the creation, and the account list is then just reloaded from the server in this case.

<mx:Button label="Delete"
  click="accountsGrid.selectedItem.id=='' ? 
      accountsIndex.send() : accountsDelete.send()"
  enabled="{accountsGrid.selectedItem!=null}" />

In the end, very little code supports the create, update, and delete functionality. In a real application, you may want to move some of the logic we added directly to the button’s click handlers to a controller class, but the underlying principles and calls are the same.

Positions

Implementing the positions functionality is very similar to implementing an account grid and services, with just a few differences. For instance, the position resource is a nested resource, so make sure the URL is set to retrieve the positions for the selected account. Another difference is that the positions resource has the custom buy action. And, finally, when a new account is selected in the accounts grid, we want to automatically retrieve the positions. Let’s get started.

As for the accounts, we declare a variable to hold the list of positions retrieved from the server:

[Bindable] private var positions:XML;

Next let’s create the grid and bind it to the positions. Again, we use an E4X instruction to get an XMLList containing each position. We also make the grid editable, although the name column is only editable when the position has not yet been saved to the server. This can be verified by the fact that no ID is assigned, which enables us to use the name column to specify the ticker to buy.

<mx:DataGrid id="positionsGrid" width="100%" height="100%"
       dataProvider="{positions.position}"
       editable="true">
  <mx:columns>
    <mx:DataGridColumn headerText="Name" dataField="name" 
      editable="{positionsGrid.selectedItem.id==''}"/>
    <mx:DataGridColumn headerText="Quantity" dataField="quantity"/>
  </mx:columns>
</mx:DataGrid> 

Now you can add the following buttons to a control bar below the data grid.

<mx:Button label="New" 
  click="addNewPosition()" 
  enabled="{positionsGrid.dataProvider!=null}" />

<mx:Button label="{XML(positionsGrid.selectedItem).id==''?'Buy New':'Buy'}" 
  click="buyPosition()" />

<mx:Button label="Sell" 
  click="sellPosition()"
  enabled="{XML(positionsGrid.selectedItem).id!=''}" />

Each of the New, Buy, and Sell buttons will invoke a corresponding function that we will implement just after creating the services. Now, as we explained earlier, you must build the create service to buy an existing stock, the delete service to sell stock, the buy service to buy a new stock, and, of course, the index service to retrieve all the positions. These services will be mapped to the URLs shown in Table 3.6.

Table 3.6  Service URL mappings

Action

Verb

Url

index
GET
/accounts/:account_id/positions
create
POST
/accounts/:account_id/positions
delete
DELETE
/accounts/:account_id/positions/:id
buy
POST
/accounts/:account_id/positions/buy

Also notice that for the nested resource, the prefix is always the same. So let’s assume we have selected the account number 2. The prefix for the positions would be /accounts/2, and the complete URL to list all the positions for that account would be /accounts/2/positions. Another example for the same account, but this time to sell the position with an ID of 3, would go like this: the URL will be /accounts/2/positions/3. Flex provides several approaches to assembling the URL with the proper account ID, and here we simply create a string in MXML using the mx:String tag and bind that string to the selected item of the accounts data grid.

<mx:String id="positionsPrefix">accounts/{accountsGrid.selectedItem.id}</mx:String>

We named this string positionsPrefix and will use it in all the URLs for the positions resource. Now each time we issue the send command for a service, the selected account ID is automatically part of the URL. Create the index service as follows:

<mx:HTTPService id="positionsIndex" 
    url="{CONTEXT_URL}/{positionsPrefix}/positions" 
    resultFormat="e4x" 
    result="positions=event.result as XML"/>

Note the binding to the positionsPrefix string in the URL. The result of this service sets the positions variable we declared earlier, and as this variable is bound to positionsGrid, the grid reloads automatically.

The create and the buy services are declared with the same parameters, with only the URLs being different. Both are used to buy stock, but in the first situation, you need to pass the ID of the position, and in the second, the ticker of the stock you want to buy. Now this could have been implemented differently, and we could have used only one action and passed different parameters to differentiate the two situations, or we could even have checked whether the ID is a string and assumed you wanted to buy new stock.

<mx:HTTPService id="positionsCreate"  
    url="{CONTEXT_URL}/{positionsPrefix}/positions"
    method="POST" resultFormat="e4x" contentType="application/xml"
    result="positionsIndex.send()"  />

<mx:HTTPService id="positionsBuy"  
    url="{CONTEXT_URL}/{positionsPrefix}/positions/buy"
    method="POST" resultFormat="e4x" contentType="application/xml"
    result="positionsIndex.send()"  />

Now the delete service is used to sell stock, so it differs from the accounts delete service in the way that we will need to pass additional information parameters to the send call. So you cannot just define the required _method request parameter using the mx:request attribute of the service declaration, as it would be ignored when issuing the send call with parameters. We can, however, stick the _method parameter at the end of URL.

<mx:HTTPService id="positionsDelete"
  url="{CONTEXT_URL}/{positionsPrefix}/positions/
     {positionsGrid.selectedItem.id}?_method=delete"
    method="POST" resultFormat="e4x" contentType="application/xml"
    result="positionsIndex.send()">                           

You created the New, Buy, and Sell buttons to invoke respectively the addNewPosition, buyPosition, and sellPosition functions when clicked. Now that we have the services declared, let’s code these functions. The addNewPosition function simply adds a <position /> XML node to the positions variable which, via data binding, adds a row to the positions grid where you now can enter the ticker name of the stock you desire to buy and specify the quantity.

private function addNewPosition():void {
  positions.appendChild(<position><id/><name>enter ticker</name></position>);
}

The buyPosition function determines if you are buying new or existing stock by checking the ID of the currently selected position. In the case of a new stock, we used the name column to accept the ticker, but the Rails controller expects a :ticker parameter; therefore, we copy the XML and add a ticker element to it. For existing stock, we send the information entered in the grid.

private function buyPosition():void {
  if (positionsGrid.selectedItem.id=='') { 
    var newStock:XML = (positionsGrid.selectedItem as XML).copy(); 
    newStock.ticker = <ticker>{newStock.name.toString()}</ticker>;                         
    positionsBuy.send(newStock)
  } else {
    positionsCreate.send(positionsGrid.selectedItem)
  }
} 

To sell a position, we pass the id and ticker to the send call.

private function sellPosition():void {
  var position:XML = 
  <position>
    <id>{positionsGrid.selectedItem.id.toString()}</id>
    <ticker>{positionsGrid.selectedItem.ticker.toString()}</ticker>                                 
    <quantity>{positionsGrid.selectedItem.quantity.toString()}</quantity>
  </position>
  positionsDelete.send(position);
}   

Next, we want the positions grid to reload when the account is changed. We can do this by adding a change handler to the accounts data grid. Here you may just want to clear out the positions and movements variables before performing the call to avoid showing for the duration of the remote call the positions of the previously selected account. Then, if it’s not a new account, you can invoke send on the positionsIndex.

<mx:DataGrid  id="accountsGrid" width="100%" height="100%"
    dataProvider="{accounts.account}"
    change="positions=movements=null; 
        if (event.target.selectedItem.id!='') positionsIndex.send()"
    editable="true">

Movements

The movements are much simpler than accounts and positions, since we just want to display the list of movements for the selected position of the selected account. So, for the index service, you can simply bind the selected account and selected position to the URL as follows:

<mx:HTTPService id="movementsIndex"
   url="{CONTEXT_URL}/accounts/
        {accountsGrid.selectedItem.id}/positions/
        {positionsGrid.selectedItem.id}/movements" 
   resultFormat="e4x"
   result="movements=event.result as XML"/>

You also need to declare the following variable to keep the results

[Bindable] private var movements:XML; 

Then you just need to declare the following grid, which is bound to the movements variable. This time, we don’t specify that the grid is editable because the movements are read only.

<mx:DataGrid id="movementsGrid" width="100%" height="100%"
       dataProvider="{movements.movement}">
  <mx:columns>
    <mx:DataGridColumn headerText="Operation" dataField="operation"/>
    <mx:DataGridColumn headerText="Quantity" dataField="quantity"/>
    <mx:DataGridColumn headerText="Price" dataField="price"/>
  </mx:columns>
</mx:DataGrid> 

When selecting a new account, we simply want to clear out the movements grid. So we need to add this to the accounts grid change handler:

<mx:DataGrid  id="accountsGrid" width="100%" height="100%"       
    dataProvider="{accounts.account}"
    change="positions=movements=null; if (event.target.selectedItem.id!='') positionsIndex.send()"
    editable="true">

And, finally, when selecting a new position, we want to request the movements for that position. We can achieve this with the following change handler on the positions grid. Again, we clear the movements before issuing the call:

<mx:DataGrid id="positionsGrid" width="100%" height="100%"
       dataProvider="{positions.position}"
       change="movements=null; 
             if (accountsGrid.selectedItem.id!='' &amp;&amp;  
                 positionsGrid.selectedItem.id!='') movementsIndex.send()"
       editable="true">

Note that when placing code directly in the MXML declarations, you cannot use the ampersand character directly due to the parsing rules of XML on which MXML is based; otherwise, you get a compiler error. So, in the above code, we need to replace the logical AND expression && with its XML-friendly equivalent: &amp;&amp;. This issue is avoided when writing code inside an mx:Script tag due to the use of the XML CDATA construct, which indicates to the XML parser that anything between the CDATA start indicator and end indicator is not XML, therefore allowing the use of the ampersand character.

Et voila! You can now create and maintain accounts, buy and sell stock, and see the movements for these positions. In this Flex application, we directly linked the services to the data grid and directly added logic in the different event handlers, and this makes explaining the code easier as you have everything in one file. This is definitely not a best practice, and for a real application, you may want to consider using an MVC framework to decouple the code and make the application more modular.

  • + Share This
  • 🔖 Save To Your Account