Flex Dynamic Scaffolding for Ruby on Rails.
No I am not announcing the next killer scaffolding framework but I had a couple of hours available today so I just explored some of the cool features or Ruby On Rails and Flex. The part I was most interested in (today) is dynamic user interface creation and not generating and application like several scaffolding frameworks are doing. So I was able to create a UI that adapts to a given model of a Rails application. Of course I didn’t go as far as I wished, but I thought I could share it with my readers as I usually get valuable feedback. Right now the application doesn’t even manage data. That will be the next step.

In a first phase I have adapted RaildRoad Rails model class diagram generation tool to generate an xml definition that the UI would use to create it’s components. I generated an xml model for Sports a sample application provided with Streamlined and Typo a blog server.
The UI generation from the typo model is quite cpu intensive. There is not lazy instanciation of components, when you select the model, all the Tabs, lists and forms are created.
You can run the application and press view source from the context menu. Or you can see the source here. The generated xml can be seen here and here
In a second phase I created a Flex application that generates a UI from the given xml.
I was writing this blog entry while coding, so if you are more curious about how all this works, keep on reading.
Getting the schema of your ActiveRecords
We will generate an xml version of the schema that Flex can use to assemble a UI. So we need to find out info about each ActiveRecord of the application, it’s association with other ActiveRecords, and all it’s attributes. Later on would also be nice to identify the validation rules, so that we can build some validations on the fly without having to do a server round trip for some of the basic validations, (required, length, confirmation, regex). Supporting the various acts_as could also provide lots of functionality that doesn’t need to be coded over and over.
I will use the Streamlined Sports example database to experiment with. Later on we may have a look at Typo a blog server.
Let’s use the community to see how to parse the ActiveRecord. I am now checking out RailRoad (0.4.0) a class diagram generator for Rails. Railroad has the ModelsDiagram class that gather the information we need and then uses the DiagramGraph class to generate a dot format file that in turn is used to generate .svg or .png of the diagram. We are not interested in the dot generation, but will just ‘adapt’ the to_dot method to get the xml we need. So I simply reopened the class and created a new to_dot method as follows:
# http://chadfowler.com/2007/8/3/enumerable-injecting
module Enumerable
def injecting(s)
inject(s) do |k, i|
yield(k, i); k
end
end
end
class DiagramGraph
def to_dot
return definition.to_xml(:root => 'active_records', :dasherize => false)
end
#Let organize the data in a way closer to the xml we want to generate.
def definition
active_records = {}
@nodes.each do |node|
attributes = node[2].injecting({}) {|accumulator, value| k,v=value.split(" :"); accumulator[k] = v}
class_name = node[1]
active_records[class_name] = { :name => class_name, :attributes => attributes, :relations => [] }
end
@edges.each do |edge|
association_type = edge[0]
from_class_name = edge[1]
to_class_name = edge[2]
active_records[from_class_name][:relations] << {association_type.to_sym => to_class_name}
end
active_records
end
endThe definition method generates a hash map with the information of the model. The to_xml is all that is needed to get an xml version of the data that the map contains.
definition.to_xml(:root => 'active_records', :dasherize => false)Dynamically Generate a Flex UI
Let looks at the model.
Player has_many Sponsor
Coach has_many Sponsor
Team has_one Coach
has_many Player
Sponsor has nobody!
The UI generation should be lot smarter and configurable. For now I have taken the approach to create one view for each model. This view shows all the records in a data grid and the detail of the selected record in a form view. All associations of the record are represented by a Tab Navigator. You will notice that this is not very practical for the Typo datamodel. We should have main ActiveRecords that are entry points to the application. Also the depth of the active record view is one association down but could be driven by definition i.e. Team => Coach => Sponsor, similar to the :include option of the find methods. We should be able to flatten a “to one” relation and have all the attributes of the association in the same view than the source ActiveRecord.
You can run the application and view the source.
The main application, FlexScaffolding, adds dynamically a ActiveRecordsView for each ActiveRecord in the model to the Tab navigator. That’s too many tabs for the Typo model…
private function generateView():void {
for each (var activeRecord:XML in definition.children()) {
var arView:ActiveRecordsView = new ActiveRecordsView();
arView.definition = activeRecord;
mainView.addChild(arView);
}
} The ActiveRecordsView.mxml does the main work of generating the UI. It’s not very big (66 lines), but is also limited for now. I let you check out the source code if you a curious. Next on the list is to map too more data types (ie a “text” ActiveRecord attribute should be mapped to a TextArea, date and datetime should be support). I need to add configuration options where the defaults can be overridden. I need to create a Rails controller that uses the same xml model to expose the data to the view. There shouldn’t be the need to hand code RESTFul controllers. Or maybe the UI should be build from the routes…
That’s all for now. Enjoy!
Daniel Wanja
On The (onAIR) Bus - Denvers stop live coverage!

Not really on the bus but at the onairbustour stop in Denver. Check out Flickr Tags (onairbustour and onair2007denver). Today’s agenda looks quite interested and there will lots of info regarding Adobe’s AIR technology. The Keynote by Ryan Stewart will start in 1 minutes. I’ll take some notes during the day…so check back!
Keynote
Ryan now shows pownce (I am still waiting for my invite…I tried to get one via inviteshare but no success yet!). He shows the nice finetune application that has a nice AIR application to complement their website. He demoes a word processor (buzzword) created in Flex and AIR, ask your preview here.
Now Ryan shows the AIR Roadmap, next big steps is Max 2007. Beta 2 will be release around Max 2007 which will add functionality like Flash AIR Support. An AIR version support Linux appear in the AIR 1.x version.
Now back to Mike Chambers that will provide a technical introduction on AIR and will create a Hello World application. At the end of the presentation Mike points to http://code.google.com/p/onairbustour/ where the post the various applications they are building on the tour about the tour.
Kevin Hoyt – AIR application with javascript
What a slacker Kevin is…only two slides :-) No it’s pretty cool, Kevin is a hands on guys and is building some AIR javascript application live and shows some nice tricks.
I won’t transcode all the code he show, but there is a tight integration between javascript and actionscript. He shows how to call directly actionscript methods from javascript.
Javascript calling Actionscriptfunction doSave() { var file = air.File.desktopDirectory.resolve("denver.txt") air.FileStream().open (...) // some code left out. }
So this is javascript and the air object allows access to Actionscript. In this case he is saving some text entered in htm l to the file system. Cool.
He presents Aptana and shows that they have some AIR integration. Check out Kevin’s blog
Kevin Hoyt – Another session on script bridging.
Kevin now builds a web browser in AIR/Flex that uses the mx:HTML component.
web.htmlControl.load(new URLRequest(address.text)) <mx:HTML id="web" />
The following provides access to any public actionscript class described in library.swf to javascript.
<script src="library.swf" />
Lunch!!!
All right, I didn’t catch up the beginning of Daniel Dura’s talk…Sorry, I was playing with my EVDO card.
Daniel Dura – AIR API Overview
Daniel describes the various apis and shows lots of code. He starts showing the different options the Window API offers (transparent, system, dialog, lightweight). He shows the Drag and Drop API (AIR to AIR, AIR to OS, OS to AIR, Desktop to AIR). It’s pretty cool to see all these APIs in action. The Service Monitoring allows to detected network connection changes.
Database Support: just added SQL integration to the new beta. Fully local database. Can be used to sync data with an online application. You can store data while being offline. He demonstrates an example written by Christophe Conraets show the SQLite integration (SQLQueue, SQLStatement).
Salesforce.com
Salesforce and Flex was used to improve the User Experience they where providing before.
Contest to give away schwag
Yea, Kevin Hoyt got taped at the back of bus…I rememberd that…answered Mike Chambers question..and won the following 7 books:

Yahoo Media Innovation Group – Jason
Some demos of what Yahoo is doing with AIR. One application is Minibar, a Dashboard like widget.
Developing AIR Applications with Ajax Components – Andre Charland from Nitobi
Why Ajax in AIR?
- Code Reuse, Skills Reuse, HTML is REALLY good at some things, Maintain UI Patterns, Javascript is growing.
- Files, Windows & Chrome, Drag&Drop, Copy&Paste, Offline, Background process, notifications, keyboard shortcuts.
- Ajax Fisheye Menu (mac like dock)
- Offline Sales Force
eBay San Dimas – Sean Chirstmann from EffectiveUI
San Dimas is eBay on the Desktop build with AIR. Why? What’s the point? This is a big question for many AIR applications. New experience for customers and new functionality AIR provides. For example alerts, notifications and the live nature of Flash is a big deal to the user.
- Development Pattern
- San Dimas is built on Cairngorm
- Assets externalized to allow for new skins
- String externalized for internationalization
- eBay SDK Overview*
- AS3 classes generated from eBay WSDL
- Objects in AS3 are serialized into XML and sent to server
- XML received from server is assembled into corresponding AS3 objects
- Benefit from working with typed native objects that are bindable
- Upcoming Features
- eBay: Browsing, Selling
- AIR: SQL database integration for category/attribute info
- OS Alerts, System Tray
see http://projectsandimas.com
Transitioning to the Desktop – Lee from frog design
The presentation will mostly focus on design. Lee also likes Microsoft products, so he can provide some perspective.
Lee did the bus wrap for the tour. Some interactive part of the onAir website. His blog is the theflexblog.com
Lee is actually showing some cool stuff done with AIR just to highlight animation and custom chrome performance. He will post these examples on his blog.
Buzzword

Cool I just go my invite. Man just logged in and it’s refreshing to see such such a cool word processor. Hehe, bye-bye word! Well, I don’t use Word anymore anyhow.
The Schedule for the rest of the onAIR tour

The bus in the bus!!!

The Kevin in the bus!!!

RailsLogVisualizer meets Adobe AIR
I recompiled the Log Visualizer with Adobe AIR. You can download it here.

I tried it under Windows XP (Parallels) and it seems that the File.browseForOpen doesn’t fire the Event.SELECT event under Windows. So the bug is that you can open a file, but the application doesn’t know when you selected it. I was contacted by Logan today who wanted to know if there is a Windows version. So sorry for the Windows users out there for the moment. Note that the Apollo version of the Log Visualizer was working under windows.
Download: RailsLogVisualizer0.5.air
Open For Business: eBay Desktop Beta - an Adobe AIR Application.
The invitations are going out! So, if you haven’t yet, go signup for the eBay Desktop beta (code name Project “San Dimas”“) at ”http://www.projectsandimas.com/">http://www.projectsandimas.com/.
The eBay Desktop is an Apollo Application, oops, Adobe AIR application, that is developed by our friends Tony Hillerson and Sean Christmann from EffetiveUI for eBay. As they had their hand full applying the finishing touch to the beta, they asked Lee and myself to help with the beta Signup program and administration site which is a Ruby on Rails application. How cool is that! Thanks guys for the opportunity to work on such a visible project…
Now if you know Sean you will understand why using the eBay Desktop is fun. When Sean is not coding he is playing games, and he want’s any application to be fun and playful. Even when he gives talks he manages to demonstrates how to program a WII controller. It’s cool that Alan Lewis gave them the creative freedom to create some new user experience concepts on top of the existing eBay apis.
Ken, my desk neighbor at one of my clients asked why would you need something like Adobe AIR? Well in the case of the eBay Desktop, you are provided with an immersive experience, having a dedicated application will encourage the user to stay within that application and not get (too) distracted. The desktop also allows to save custom searches and additional information locally, thus providing functionality that may not be available by the existing eBay apis. It could also allow for functionality like drag&drop of images and text from the file system to create online auctions, use a connected camera to snap pictures, scan bar codes to retrieve product information, and so on…

PS: Hey Sean what’s your blog…or are you too busy coding?
The New SearchCoders Apollo Dashboard
![]()
The new version of SearchCoders is not just a pretty face, Tom and Robert also worked hard adding quite some neat and useful functionality like chatroom, notes and favorites. Searching is faster than ever. The new Searchcoders.com Dashboard is Still the best way to find useful Flex related information on the net.

Web Snapshot - a simple Apollo Application.
This simple Apollo Application takes 200×150 thumbnails of a Web page.
UPDATE: See Web Snapshot – a simple Adobe AIR application
1) Enter the URL of the page you want to “Snap”.
2) Click the Thumbnail
3) A file dialog opens and asks for the File to save.
Download it now: WebSnapshot0.1.air (right click and ‘Download Linked File’)
It uses the new HTMLControl that Apollo provides, which behind the scene is a full fledged web browser based on KTHML. Check out an extract of the source code:
//1. Load the page (asynchronously) var html:HTMLControl = new HTMLControl(); html.width = 400; html.height = 300; html.load(new URLRequest(url)); //2. Draw and scale the rendered html into a bitmap var snapshot:BitmapData = new BitmapData(200, 150); var matrix:Matrix = new Matrix(); var scaleX:Number = 0.5; var scaleY:Number = 0.5; matrix.scale(scaleX, scaleY); snapshot.draw(htmlContent, matrix); //3. Save as JPEG var jpegEnc:JPEGEncoder = new JPEGEncoder(75); var jpegData:ByteArray = jpegEnc.encode(snapshot); var stream:FileStream = new FileStream() stream.open(file, FileMode.WRITE); stream.writeBytes(jpegData); stream.close();
I found the JPEGEncoder here.
And Daniel Dura had a trick to use a native save windows.
Note I need to try this application on Windows…I’ll do that tomorrow.
Enjoy!
Daniel
Update:I quickly tried on Windows XP and the save doesn’t seem to work. Let me know how it works for you. Thanks.
RailsLogVisualizer meets Apollo.
It’s not complete yet, but for the curious out there, here is a first and “ruff” version of the RailsLogVisualizer as a pure Apollo application. The previous version was an OSX application that was embedding a Ruby http server that was used to load the Rails log files, as a Flex application didn’t provide a mean to load files directly. Here comes Apollo and lifts that restriction. So I thought…let’s try to rewrite the file loading in Actionscript. Well this is my first attempt, during the port I broke a couple of features that will need more attention in the future. Also I haven’t tried to load any file bigger than 40Mb. And I haven’t implemeted the incremental loading of large files that I had with the Ruby version. Also the keyboard navigation isn’t working…so just use the mouse for now. That’s the next thing I’ll need to fix. Let me know what you find at daniel@onrails.org or just add some comments on this entry.
Things that broke during the port:
- Hourly breakdown of daily request.
- Breakdown ofHttp methods (Get, post, delete, head).
Things I’ll need to add next:
- Improve progress indicator during file load and data parsing.
- Refactor interaction to allow keyboard support (basically rewrite using Cairngorm).
- Improve the File Browser.
- Support for RESTFull controllers (detect method parameters (i.e. ?method=put)).
- Add chart of action over time.
How to install:
1) If you haven’t yet downloaded the Apollo Runtime, get it here: Apollo runtime (8Mb).
2) Download the Rails Log Visualizer:
RailsLogVisualizer0.4.air (480Kb) (right click and ‘Download Linked File’). On a side note don’t click directly as the mime type on this server for .air files is not yet set. For more info see Mike Chambers entry on the subject.
3) Follow the installation steps that Apollo provides. It’s a little strange at first as they have a custom installer.
Searchcoders.com - the fastest way to search the Flexcoders group.
Tom and Robert just announced that Searchcoders.com went live. I had the chance to have met Tom and Robert at the 360flex conference and they gave me access to the beta of searchcoders.com. I have used google, the yahoo groups and several other means before to search through all the messages of the flexcoders group, and searchcoders.com just works the best for me. This group just has so much great content and is the fastest way to solve many of the issues you may
encounter once you start pushing what Flex has to offer. Thank to the community of sharing all this info and thanks to Searchcoders to make it more valuable and more accessible.
Best way to reset a form using Cairngorm?
I just implemented some code that doesn’t feel quite right, but works and would like your input on the matter. A Payment Entry form will be used by the user several times in the life of a Flex application to enter different type of payments. So every time the user wants to pay, the form needs to cleared. I can see these different ways:
1. Ask the form to clear all it’s fields
2. Bind the fields to a model, and reset the model with the default fields values
3. Create a new instance of the form.
It’s a rather complex form with multiple steps (tabs) and the user can quit the form at any moment. So option 1 and 2 needs to reset not only the fields but also the state of each component used on the form. Therefore I opted for approach three which goes as follows:
The view contains following code that replaces the form with a new instance:
public function clearPaymentInformation():void {
var index:Number = content.getChildIndex(enterPaymentView);
content.removeChild(enterPaymentView);
enterPaymentView = new EnterPaymentInformation()
content.addChildAt(enterPaymentView, index);
}Now we have a PayInvoiceCommand that needs to invoke this function. That’s where what doesn’t feel right as the command has to know the view. With the newer version of Cairngorm the command gets information using a delegate, then updates the model. The view is bound to the model. But the command shouldn’t have to know the view. But for option 3 I didn’t find another way around. So I use an adapted version of the ViewLocator (as my view are not ViewHelpers) to which I register the view upon creation. Then in the command I use
WebComponentsViewLocator.getInstance().getView("paymentView").clearPaymentInformation();
model.paymentViewState = WebComponentsModelLocator.PAYMENT_VIEW_STATE_ENTER_PAYMENT;Is there anyone out there that uses the same approach. If no, thats maybe a good answer that I am on the wrong track. Maybe I should issue an event from the command and have the view listen to the event. This would decouple both, but still doesn’t feel quite right. Maybe I just had a too long day. So any insight is welcome on how you deal with “reseting” forms in your Cairgorm applications. Thanks in advance.
Time for MotorStorm!
360Flex - Day three
08:30am Last day’s Keynote by Ted Patrick
Tom Hobbs from the Experience Design group of Adobe presents how they developed the Tour Tracker a complex application tracking a cycling race with gps locations of the racers, links to Flickr feeds of the photo, video. It was done by 3 people in 6 weeks. Tom goes in detail through the iterative development they used, the team started building upfront and gradually added complexity. He presented the values the team where using to reach a great design. Great talk.
![]()
And now Ted Patrick on the “Next Flex”. He wants to talk about what Adobe and the people using Flex are working on. What he is going to show us may not ship, Adobe tries to be open about what they are working on but may decide not to deliver it or deliver it later. They want to expand the reach of RIAs to include desktop, web and offline applications. They want to make it easier for web and enterprise application developers to learn Flex. They want to invest in the platform to server the needs of enterprises and the Flex ecosystem. They want to be much more Open and transparent, they want to build the next generation of Flex with everyone that is working with it. They are two release of Flex set for this year, Moxie and Borneo. The next generation of Flex will be build on the Flash Player 9. They want to better integrate Flex with CS3 (Flash, Fireworks, Illustrator and Photoshop). He now stops and show the integration with Fireworks. In Fireworks he can drag Flex components on a Fireworks image. FW implements scale 9. Is building a UI in Fireworks. In FW he can changes the properties of a Flex components. The he can export the image a MXML and images. Now a designer can prototype a Flex application without using Flex right from Fireworks. The next piece of the puzzle is “Borneo”, the next version of the Flex Data Services. Integrates with LifeCycle. The team has rewritten the mx:WebService to support better SOAP. Moxie is the next version of the Flex SDK and Flex Builder with improved “Language Intelligence”, integrated Profiler, enhanced Design View, Data integration, enhanced DataGrid and Lists. He now shows a demo of it. FlexBuilder 3 now has a refactor method where a method can be renamed right from it’s use. It has also variable renaming. command-shift-j finds cross class all the uses of a given method/variable. Flex and Apollo They are working on a Apollo plugin for Eclipse. Will be release at Apollo camp on March 16th. FlexBuilder will host an Apollo Project. Flex Ecosystem Flex is more than Adobe. It’s fantastic. He now shows some examples. ESRI, the world is not flat! ESRI created a set of components to allow vector mapping to be included in a Flex app with one or two tabs. Ted now shows a demo of these components. The next demo is from Farata Systems. Their background is from the PowerBuilder days and having lots of fun with Flex. FlexBI (Business Intelligence). He shows a customized data grid and can modify the view and the data to be retrieved. The gird is grouping, sorting and totaling the data. Now onto Flexlib. Darron Schall and Doug McCune published many of their components under the MIT license on google code. They also created a whole environment to allow the community to contribute. They have put a demo out at http://dougmccune.com/flexlib/keynote/.

Last thing is Yahoo. Yahoo provides open apis to allow 3rd party developers to make their site better. At this conference Yahoo provided the AS3 apis to their different services. Flex API Posters Everyone on the 360Flex mailing list (at the conference or on the waiting list) will get an email and will get the Flex API poster. Next 360Flex Now Ted asks Tom and John who created the conference to come up on stage and he talks about the future of the conference. Tom is asking who would be interested to do another 3 day conference in August. About half of the audience responds. He also asks who would be interested in a one day event in your city, 120Flex, and who if the topics should rather be introduction or advanced. Lots of interest for the one day event and no interest in the beginner sessions. And now three quick announcements from the Ebay team. 1) they are hiring 2) they are holding their developers conference in June 11th-13th in Boston ($350 for 3days) 3) An Ebay Actionscript open source library that is released today. Allows to use ebay easier. (http://adobe.com/go/ebaylibary, will be available shortly). Tom now thanks his team has he wasn’t very productive during this conference. End of Keynote.
11:00am Model-Driven Integration Strategies by Joe Berkovitz
Modeling: describing software abstractly
Integration: hooking up disparate components
Strategy: an overarching approach to a problem
Model-Driven Integration Strategy: An approach that uses abstract descriptions of drive the hookup of disparate components.
He will mostly talk about transformation tools: Axis, xdoclet, xdoclets2, XSLT. He will not talk about these tools directly but about Hamachi, a generator generator. Hamachi can generate Value Object, and Cairngorm classes. Hamachi use a language neutral XML format. All right…I am out of this talk. If I need Hamachi I will look it up, but some guys from Adobe are about to publish a FlexBuilder plugin for Cairngorm, that’s all I would need for now.
05:10pm Ok it’s a wrap. I am at the airport on my way back to Denver and a little dazzled. Lot’s of Flex during the last three days. But I must admit that the Flex team created an awesome platform that showed it’s potential during this conference. It’s gonna be the year of Flex and many companies at the conference (Yahoo, Allurent, Ebay, Adobe, Userplane and others) where looking for people willing to dive into Flex. There will more Flex applications developed this year than ever before. So keep an eye open for Flex. For me it’s gonna be back to consulting work tomorrow and I have a big Flex project to “finish” for the end of the month. So I may not have time to play with all the cool new stuff I learned. I hope you enjoyed my attempt of live coverage of the event. Have fun!