SYS-CON Media
 Register Now!
Save $200
Register before October 17th to SAVE! ... and also receive a FREE copy of the Best-Selling AJAX Book, a $119 Value!
Untitled Document
2008 East
Platinum Sponsor
Untitled Document
2008 East Gold Sponsors
Untitled Document
2008 East Exhibitors
Untitled Document
2008 East Media Sponsors
Untitled Document
2008 Association Sponsor
SYS-CON Media
2007 West Sponsors
Goingtomeet.com Conference Directory
SYS-CON Media
2007 East Sponsors
Untitled Document
2008 SYS-CON Events

Can't Miss RSS Feed
Subscribe to the AJAXWorld.com RSS Feed & Get All The Conference News As It Happens!

2008: Decision Year for RIAs - October 20-22, 2008 San Jose


Flex On Ruby on Rails
Automating the communication between the client and server

With the release of Flex 2, Adobe has introduced a tool that makes building rich user interfaces for the Web easier than ever; of course, as anyone remotely plugged in to the Web development community knows, Ruby on Rails has made creating database-driven Web applications brain dead simple. This article discusses a technology that marries Flex with RoR applications by providing a means of automating the communication between the client and server. The technology is "WebORB for Rails," a free and open source (GPL) server made available by Midnight Coders (www.themidnightcoders.com).

Many of the tutorials on the Web that talk about integrating Flex clients with Rails discuss using raw XML over HTTP. While this mechanism is nice for the standard "mom and apple pie" tutorial that return a simple list of records, this level of integration quickly becomes unwieldy as the complexity of the application grows. With each new operation on the server, a developer must spend valuable cycles serializing and deserializing requests and responses before they can focus on the actual business logic.

WebORB relieves the burden of this "serialization tax" by supporting the concept of remote objects whereby Flex clients can natively invoke methods on the server and retrieve the responses all within ActionScript, the object-oriented programming language used by Flex.

This article will discuss installing WebORB to "Flex-enable" a Ruby on Rails application, the steps required to create an application using Flex + WebORB + RoR, and some advanced topics like dealing with Rails models, etc.

Installing WebORB for Rails
WebORB runs as a plug-in for Rails and is installed by simply running the following command within the root directory of a Rails application. On *nix systems:

./script/plugin install http://themidnightcoders.net:8089/svn/weborb/

or on Windows:

ruby script/plugin install
http://themidnightcoders.net:8089/svn/weborb/

Writing an Application Using WebORB
There are three simple steps that are required to build a Flex-based RIA utilizing WebORB and Rails.

  1. Build the service class and drop into RAILS_APP/app/services
  2. Add an entry to RAILS_APP/config/WEB-INF/flex/remoting-config.xml for the remote service
  3. Set up a RemoteObject on the client-side using Flex that will communicate directly with the back-end service.
As a simple example consider the following service written in Ruby:

require 'weborb/context'
require 'rbconfig'
class InfoService
def getComputerInfo( requestId )
computer_info = Hash.new
request = RequestContext.get_request
computer_info['serverName'] = request.server_software
computer_info['requestId'] = requestId
computer_info['os'] = Config::CONFIG["arch"].to_s
computer_info['currentTime'] = Time.now
computer_info
end
end

This example is bundled within the WebORB on Rails product and simply returns a bag of properties related to the server running the service. Generally, the classes that are surfaced as remote objects are added to a /services directory under the RAILS_APP/app directory.

After creating this class, you must also tell Flex that this class needs to be available as a remote object. This is configured by adding the following snippet of XML to the remoting-config.xml file located within the RAILS_APP/config/WEB-INF/flex directory:

<destination id="InfoService">
<properties>
<source>InfoService</source>
</properties>
</destination>

Last, this service is invoked by a client by using the RemoteObject class within ActionScript. Below is a small chunk of code that demonstrates how to use this class:

remoteObject = new RemoteObject();
remoteObject.destination = "InfoService";
remoteObject.getComputerInfo.addEventListener("result", onResult);
remoteObject.addEventListener("fault", onFault);

Assuming that the remote object variable was declared at the top of your MXML application, this code illustrates creating and initializing a remote object for use. Note in particular that the destination property is set to "InfoService", which maps directly to the ID attribute of the destination we just configured within remoting-config.xml. Note that this is how Flex (and WebORB) determines where to send this request. The final two lines above demonstrate adding callback methods to the remote object; the first line tells Flex to pass the result of a call to the getComputerInfo method (this maps to the Rails service method on the server) to the onResult method (which is on the client). The last line tells the remoteObject instance to pass any faults to the onFault method (also implemented in ActionScript). The example below shows the two event listeners that were registered above:

public function onFault(event:FaultEvent):void
{
Alert.show(event.fault.faultString, 'Error');
}
public function onResult(event:ResultEvent):void
{
var computerInfo:Object = event.result;
serverInfoText.text = computerInfo.serverName;
requestIdText.text = computerInfo.requestId;
osText.text = computerInfo.os;
timeText.text = computerInfo.currentTime.toString();
invokeButton.enabled = true;
}

Now the remote object can invoke the method on the server written in Ruby by simply calling:

remoteObject.getComputerInfo("ABC123");

and the results will be available in the event.result object that is passed to the onResult method as demonstrated above. In this example each property that is stored on the server is available as a property of the event.result object that we store above in the computerInfo instance. The source code for this example is available as part of the WebORB distribution for those interested in looking at the complete picture; after installing WebORB the server code is available in /app/services/InfoService.rb and the client code is available in /public/examples/example.mxml.

Advanced Features of WebORB
Active Record Integration

The previous example is a simple tutorial on how integrating Flex and Rails works using WebORB and the RemoteObject class. However, when building Rails applications, most of the interesting data for your application will be available via the ActiveRecord API in the data model layer. This is actually where WebORB provides a great deal of value: it natively serializes Rails model objects to Flex clients including handling any associations that are requested as part of an active record query.

Consider the following Ruby class that can be dropped into a ProductService.rb file within /app/services:

class ProductService
def getProducts
Product.find(:all, :include => [ :images ])
end
end

This service will return all the products in the database and include associated image records; this type of service would be great for displaying a product list within a DataGrid that also could display product images upon selecting a row in the grid. On the client side the results of this method invocation could be made available in an ActionScript method such as:

public function onGetProducts(event:ResultEvent):void
{
var products:Array = event.result as Array;
dataGrid.dataProvider = products;
}

Also note that within each product, another array is available that is accessed through the images property (the Image model in rails would likely include a URL or path attribute that Flex could use to load pictures). As an example, the following ActionScript method could be attached to the "change" event of the DataGrid:

public function onProductSelected():void
{
var product:Object = dataGrid.selectedItem;
for( var i:Number = 0; i < product.images.length; i++ )
{
var imageObject:Object = product.images[i];
// do something useful with imageObject.path attribute
}
}

Last, remember that if you do not want to include associated data (has_many/belongs_to relationships within Rails models), then simply do not pass the :include option to your query.

Access to the HTTP Request and Session
As a final note, another useful feature of WebORB is the ability to access the HTTP request or session objects within remote Rails services. These objects are available to standard Rails controllers that operate at the HTTP level; however, when using WebORB, developers simply develop "services" that are server methods that generally act as a layer between clients and Active Record models without inherent knowledge of the HTTP transport protocol. There will be times, however, when a service will need access to either the HTTP request or session. This is made available through a RequestContext class that can be included in any remote service. This technique was actually used in our first example. Note the "require 'weborb/context'" line within InfoService.rb listed above; this line imports the RequestContext class so that developers can access the HTTP request and session via the respective RequestContext.get_request and RequestContext.get_session class-level methods. Any data that is stored in the session will be available to subsequent requests using the standards Rails session API after retrieving the session object similar to:

session = RequestContext.get_session
#do something interesting with the session object

Basic Authentication Support
WebORB provides support for basic authentication of client applications. This allows credentials to be set on the RemoteObject instance, and services to access the associated user name and password on the server. On the client side this is done with ActionScript using the setCredentials method on a RemoteObject instance.

remoteObject.setCredentials("UserNameHere", "PasswordHere");

This information is available using the same RequestContext API discussed above. Within your service you can get the credentials using the API demonstrated below:

require 'weborb/context'
class SecureService
def doSomethingSecretive
user = RequestContext.get_user_name
password = RequestContext.get_password
//Authenticate credentials here, if unauthorized raise error
end
end

The one problem with this approach is that now the service code is contaminated with authentication code. Ideally this would happen before ever reaching the method (like using a "before filter" in Rails controllers. WebORB will eventually provide an interface that will authenticate users in a similar way before ever reaching secure methods. In the meantime, it is important to make this feature available for developers who need this capability today (WebORB on Rails will continue to support this API even after a cleaner approach is provided).

Conclusion
This article provided an initial glimpse into how Flex clients can be integrated with Ruby on Rails using WebORB's Flex RPC implementation and the RemoteObject API. While some applications with very simple data requirements can happily integrate Flex and Rails using model.to_xml and standard HTTP requests, WebORB on Rails simplifies the development process as the amount of client/server interaction scales to a large number of request/response types.

About Harris Reynolds
Harris Reynolds has been working in software development and systems integration for the past eight years. Most recently he was an enterprise architect at Fannie Mae where he was responsible for the development of messaging architecture supporting internal integration. Prior to consulting for Fannie Mae he was a lead engineer for webMethods working on SOA infrastructure and their underlying service registry. He has also completed projects for several large companies including Amkor Technology, BASF, PricewaterhouseCoopers, and Bank of America.

In order to post a comment you need to be registered and logged in.

Register | Sign-in

Reader Feedback: Page 1 of 1

Latest AJAXWorld RIA Stories
CloudEXPO | DevOpsSUMMIT | DXWorldEXPO Silicon Valley 2019 will cover all of these tools, with the most comprehensive program and with 222 rockstar speakers throughout our industry presenting 22 Keynotes and General Sessions, 250 Breakout Sessions along 10 Tracks, as well as our ...
Big Switch's mission is to disrupt the status quo of networking with order of magnitude improvements in network e ciency, intelligence and agility by delivering Next-Generation Data Center Networking. We enable data center transformation and accelerate business velocity by delive...
Dynatrace is an application performance management software company with products for the information technology departments and digital business owners of medium and large businesses. Building the Future of Monitoring with Artificial Intelligence. Today we can collect lots and l...
Your job is mostly boring. Many of the IT operations tasks you perform on a day-to-day basis are repetitive and dull. Utilizing automation can improve your work life, automating away the drudgery and embracing the passion for technology that got you started in the first place. In...
Technological progress can be expressed as layers of abstraction - higher layers are built on top of lower layers treating them as abstract black boxes with known interfaces. A serverless approach represents an inflection point that entirely separates the runtime layer from the u...
Untitled Document

Call 201 802-3020 or Click Here to Save $200!

Register Today and
Save $200

Your registrations includes: Golden Pass Delegates will receive full conference access on October 20-22, 2008 including: Lunch and Coffee Breaks, Collectible Bag and Archives of all sessions on DVD. Includes access to all Conference Sessions including the Technical Sessions, Exhibits, Keynotes, Vendor Technology Presentations, and Power Panels.


Sponsorship Opportunities

AJAXWorld offers the undisputed best platform to position your company as a leading vendor in the fast-emerging marketplace for AJAX and Enterprise Web 2.0.


Please call
(201)802-3020


Who Should Attend?

 CTOs & VPs of Engineering
 Directors of Technology
 Sr. User Interface Architects
 Front-End Engineers
 VCs & Industry Analysts
 Directors of Business Development
 Software Engineers
 Senior Architects
 Application Programmers & Software Developers
 Project Managers
 Web Programmers & Designers
 Companies & Organizations that need to stay in
  front of the latest Web technology

AJAXWorld Security Bootcamp

Introducing at AJAXWorld RIA Conference 2008 West the world's first-ever full, one-day immersive "AJAX Security Bootcamp" - led by one of the world's foremost AJAX security experts and teachers, HP's Billy Hoffman.

View the full one-day schedule



AJAXWorld 2008 West - Tracks

Track 01: Enterprise RIAs
Track 02: Frameworks & Toolkits
Track 03: Web 2.0 & Mashups
Track 04: Hot Topics
Track 05: The Future of the Web
Track 06: iPhone Developer Summit



Brought To You By:

AJAXWorld Magazine is the pre-eminent independent vendor-neutral resource for the fastest growing new segment of the software business: entirely Web-based applications and experiences.

Download the Latest Issue!

AJAXWorld Webcasts



SYS-CON EVENTS


AJAXWorld Keynotes & Power Panels

2008 SYS-CON TV Keynotes: Can We Fix the Web? By Douglas Crockford - by Douglas Crockford
2008 SYS-CON TV Keynotes: 2008: The Year of the RIA - by Anthony Franco
2008 SYS-CON TV Power Panel: The Business Value of RIAs
2008 SYS-CON TV Power Panel: What Lies Beyond AJAX
2007 SYS-CON TV Keynotes: Why Web 2.0 for the Enterprise Is Far More Than Just a Facelift - by Ted Farrell
2007 SYS-CON TV Keynotes: Fueling the Next Generation Web: A Peek Behind the Green Curtain - by Bob Brewin
2007 SYS-CON TV Keynotes: AJAX in the Balance - by Joe Stagner

AJAXWorld Sessions on SYS-CON.TV

· Bill Scott - Yahoo! UI Library
· David Heinemeier Hansson - AJAX on Rails
· Jesse James Garrett - Elements of User Experience
· Dion Hinchcliffe - Real World AJAX
· Eric Miraglia - Open Source AJAX Development
· Paul Rademacher - Mashing Up Your Web Application
· Adam Sah - Google Gadgets
· Doug Crockford - An Introduction to JavaScript
· David Linthicum - Enterprise Web 2.0
· Patrick Grady - The Imagination & Experience Web

AJAXWorld...All The AJAX Rock Stars in One Spot!


Past Events Archive

SOAWorld Conference & Expo 2008 East
soa2008east.sys-con.com
Virtualization Conference & Expo 2008 East
virt2008east.sys-con.com
AJAXWorld 2008 Conference & Expo East
ajaxmar08.sys-con.com
SOAWorld Conference & Expo 2007 West
www.soaworld2007.com
Virtualization Conference & Expo 2007 West
virt2007west.sys-con.com
AJAXWorld 2007 Conference & Expo West
ajaxoct07.sys-con.com
SOAWorld Conference & Expo 2007 East
soa2007east.sys-con.com
Virtualization Conference & Expo 2007 East
virt2007east.sys-con.com
AJAXWorld 2007 Conference & Expo East
ajaxmarch07.sys-con.com
Other SYS-CON Events
events.sys-con.com

Join Over 10,000 Early AJAX Adopters
Who Have Attended AJAXWorld
• A&R Edelman
• Academic Enterprise
• Accoona Corp [2 delegates]
• Acxiom
• Adams Capital Management
• Adaptive Edge
• Adaptive Path
• Adobe Systems Incorporated [21 delegates]
• Adobe Systems Romania
• Ajax13
• All Risks, Ltd.
• alliance
• Alliance For Community Care
• AlphaDetail Inc
• Altera Corporation
• Amazon.com [6 delegates]
• Appeon Corporation [2 delegates]
• Apple Computer [5 delegates]
• Apress [3 delegates]
• Arkivio
• ASA
• Astute Solutions
• Avaya Inc [2 delegates]
• Avenda Systems
• Avenue A | Razorfish [3 delegates]
• Axcella, LLC [2 delegates]
• Aximsoft
• Azimyth
• Backbase USA Inc. [4 delegates]
• BAE Systems [2 delegates]
• Bank of America [2 delegates]
• Barkley Evergreen & Partners Interactive
• Bayview Financial [2 delegates]
• BEA Systems [3 delegates]
• Billeo
• BMC Software, Inc. [2 delegates]
• Borland Software Corporation
• Bradford Technologies, Inc [2 delegates]
• Brilliance
• Brocade Communications Systems, Inc. [2 delegates]
• Brookside Capital LLC
• Brulant
• Bungee Labs, Inc [6 delegates]
• Bureau of Labor Statistics
• BUZ Interactive
• Cadena Software
• Calix Networks
• Callidus Software [2 delegates]
• Cambia Security
• Carnegie Mellon West
• Cautella, Inc.
• CBSA
• Celequest [3 delegates]
• Change Vision, Inc.
• Charles E. Kenney, CPA
• Charles Schwab & Co., Inc. [8 delegates]

   read more...


ADVERTISE   |   MAGAZINE SUBSCRIPTIONS   |   FREE BREAKING-NEWSLETTERS!   |   SYS-CON.TV   |   BLOG-N-PLAY!   |   WEBCAST   |   EDUCATION   |   RESEARCH

.NET Developer's Journal - .NETDJ   |   ColdFusion Developer's Journal - CFDJ   |   Eclipse Developer's Journal - EDJ   |   Enterprise Open Source Magazine - EOS
Open Web Developer's Journal - OPEN WEB   |   iPhone Developer's Journal - iPHONE   |   Virtualization - Virtualization   |   Java Developer's Journal - JDJ   |   Linux.SYS-CON.com
PowerBuilder Developer's Journal - PBDJ   |   SEO / SEM Journal - SJ   |   SOAWorld Magazine - SOAWM   |   IT Solutions Guide - ITSG   |   Symbian Developer's Journal - SDJ
WebLogic Developer's Journal - WLDJ   |   WebSphere Journal - WJ   |   Wireless Business & Technology - WBT   |   XML-Journal - XMLJ   |   Internet Video - iTV
Flex Developer's Journal - Flex   |   AJAXWorld Magazine - AWM   |   Silverlight Developer's Journal - SLDJ   |   PHP.SYS-CON.com   |   Web 2.0 Journal - WEB2

SYS-CON MEDIA:   ABOUT US   |   CONTACT US   |   COMPANY NEWS   |   CAREERS   |   SITE MAP
SYS-CON EVENTS  |  AJAXWorld Conference & Expo  |  iPhone Developer Summit  |  OpenWeb Developer Summit  |  SOA World Conference & Expo  |  Virtualization Conference & Expo
INTERNATIONAL SITES:   India  |  U.K.  |  Canada  |  Germany  |  France  |  Australia  |  Italy  |  Spain  |  Netherlands  |  Brazil  |  Belgium
 Terms of Use & Our Privacy Statement     About Newsfeeds / Video Feeds
Copyright ©1994-2008 SYS-CON Publications, Inc. All Rights Reserved. All marks are trademarks of SYS-CON Media.
Reproduction in whole or in part in any form or medium without express written permission of SYS-CON Publications, Inc. is prohibited.