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

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020