XML Filtering Predicate

I need to filter some XML data based on several conditions. I found the following article “”http://www.darronschall.com/weblog/archives/000214.cfm">E4X: Predicate Filtering with Regular Expressions" from Darron that provides a nice overview of filtering using e4x. I haven’t found any more detailed information on using predicates so I checked out the ECMAScript for XML
(E4X) Specification 2nd edition
. See page 52 for details. But in short the filter can be an expression and use && and ||, the logical and and or.

filtered = list.item.( /^4567./.test( number ) || /^D./.test( name ) );

Here is the full test case:

package tests.actionscript
{

import flexunit.framework.*;

public class TestXml extends TestCase
{

public function testXMLFiltering():void {
var list:XML =
Kamesh
12345


Daniel
12345


Robin
12345


George
4567


Adam
4567


Dean
4567 yes
var filtered:XMLList = list.item.( /^D./.test( name ) ); Assert.assertEquals(2, new XMLListCollection(filtered).length);
filtered = list.item.( /^4567.
/.test( number ) );
Assert.assertEquals(3, new XMLListCollection(filtered).length);

filtered = list.item.( /^4567./.test( number ) && /^D./.test( name ) );
Assert.assertEquals(1, new XMLListCollection(filtered).length);

filtered = list.item.( /^4567./.test( number ) || /^D./.test( name ) );
Assert.assertEquals(4, new XMLListCollection(filtered).length);

}

} // class

} // package

Flex introspection API: describeType(value:*):XML

I am playing with the mx.automation framework provided by Flex. For that I need to associate each control with it’s automation implementation. More on that on a subsequent blog entry. But it some case I need to find the super class of a class

Let’s take the following three classes:

class A {}
class B extends A {}
class Tab extends Button {}

Now we can create the following function:

import flash.utils.describeType;
private function superClass(clazz:Class):String {
return describeType(clazz).factory.extendsClass0.@type;
}

Let run the following code

trace(“A super class:”superClass(A));
trace(“B super class:”
superClass(B));
trace(“Tab super class:”+superClass(Tab));

And we get the following output:

A super class:Object
B super class:com.nouvelles_solutions::A
Tab super class:mx.controls::Button

Let me know if there is an easier way.

The build in describeType function takes a class as parameter and return an XML definition of a class. For example describeType(B) returns the following:












Pretty cool.

Cairngorm Generators

I looked into Cairngorm a while ago (version 0.95 I believe, pre-ModelLocator area) and didn’t like the fact that you couldn’t use Flex bindings at that time. I recently gave it a second look I liked what I saw. Using Cairngorm is at first very verbose but it provides you with a clear way of organizing your code, which is very beneficial on larger projects. Cairngorm is well documented and there are several nice examples available. Also checkout http://www.cairngormdocs.org/. So yesterday introduced Cairgorm on two Flex projects I am working on.

The first project is a larger Flex 1.5 project (65 actionscript classes, 75 Data transfer object, >100 Mxml views) that I need to migrate to Flex 2.0. I though “great time to start with Cairngorm”. So the first step was to look at all the user gestures for all the screens and create a list of events, map these events to commands, create 3 delegates and services to handle all the remote calls. On paper that was pretty fast to do, but I didn’t want to create all the Cairngorm supporting class by hand. Handily I found the following generator that is a PHP application:

Cairngen


It targets currently only Cairngorm 2.0 and not the newer Cairngorm 2.1. So after generate the supporting classes I had to manually do some changes. But thanks for this tool.

The second project is a smaller Flex application backed by a Ruby on Rails server. And I found the following Ruby on Rails Cairngorm generators at http://code.google.com/p/cairngorm-rails-generator/

Simply copy the generators to your “/vendor/generators” folder, the generators folder will then contain the following generators:

cairngorm
command
delegate
event
vo
worbservice

Note there are several places in Rails you can set generators, but that did the trick for me. The I created a “src” folder in my Rails root folder and issues the following commands:

Then you can use these different generator commands to build the structure you require, the events, commands, delegates and more.

./script/generate cairngorm org/onrails/myspyder
./script/generate delegate org/onrails/myspyder server
./script/generate command org/onrails/myspyder show_page_watch server
./script/generate event org/onrails/myspyder show_page_watch

I issued the generate script for each of the commands that application needs to support. The main controller now looks as follows (still very early in the development phase)

package org.onrails.myspyder.control
{
import com.adobe.cairngorm.control.FrontController;
import com.adobe.cairngorm.control.CairngormEventDispatcher;
import org.onrails.myspyder.control.;
import org.onrails.myspyder.command.
;

public class MySpyderController extends FrontController
{
public function MySpyderController()
{
initialiseCommands();
}

public function initialiseCommands() : void
{
// Application Tabs
addCommand( ShowAccountEvent.EVENT_SHOW_ACCOUNT, ShowAccountCommand );
addCommand( ShowPagesEvent.EVENT_SHOW_PAGES, ShowPagesCommand );
addCommand( ShowSettingsEvent.EVENT_SHOW_SETTINGS, ShowSettingsCommand );

// Page List
addCommand( ReloadPagesEvent.EVENT_RELOAD_PAGES, ReloadPagesCommand );
addCommand( AddPageEvent.EVENT_ADD_PAGE, AddPageCommand );
addCommand( ReloadPageEvent.EVENT_RELOAD_PAGE, ReloadPageCommand );
addCommand( RemovePageEvent.EVENT_REMOVE_PAGE, RemovePageCommand );
addCommand( SavePageEvent.EVENT_SAVE_PAGE, SavePageCommand );

// Page Details
addCommand( ShowPageWatchEvent.EVENT_SHOW_PAGE_WATCH, ShowPageWatchCommand );
addCommand( ShowPageWatchResultEvent.EVENT_SHOW_PAGE_WATCH_RESULT, ShowPageWatchResultCommand );

// Html Section
addCommand( ShowOriginalPageEvent.EVENT_SHOW_ORIGINAL_PAGE, ShowOriginalPageCommand );
addCommand( ShowPageSectionEvent.EVENT_SHOW_PAGE_SECTION, ShowPageSectionCommand );
addCommand( SelectPageSectionEvent.EVENT_SELECT_PAGE_SECTION, SelectPageSectionCommand );

}

}

}

Let me know your experience with Flex and Cairngorm.

Auto-loading Ruby Code

An incredibly useful technique when using Ruby is to auto-load at start-up a custom library written for exactly that purpose. This is easy to accomplish with a couple of environment variables, but I see very little discussion on the subject. Thus, I’ve written a nice summary of how to go about setting this up.

The secret to running code at start-up is RUBYOPT. You’ve probably seen this environment variable before if you’ve used RubyGems. It is recommended to set this to a value of rubygems. This is equivalent to always calling ruby as ruby -rubygems. The -r option requires a library, so this option essentially does a require 'ubygems' each time Ruby is started. (The odd name of ubygems was picked to look nice next to -r.)

We’re going to be doing something similar, but with our own library. I’ve traditionally put this file in ~/.ruby/lib/tpope.rb, but I will be using the more user-agnostic mine.rb for the purposes of this example.

The first thing we need to do is find the right place to set this environment variable, along with setting RUBYLIB to a path that holds our file. If you are using a bourne compatible shell, like bash, add this to your shell’s rc file (~/.bashrc for bash):

if [ -f "$HOME/.ruby/lib/mine.rb" ]; then
  RUBYLIB="$HOME/.ruby/lib"
  RUBYOPT="rmine"
  export RUBYLIB RUBYOPT
fi

For C shells, add the following to ~/.cshrc:

if ( -f "$HOME/.ruby/lib/mine.rb" ) then
  setenv RUBYLIB "$HOME/.ruby/lib"
  setenv RUBYOPT "rmine"
endif

If you are running under a GUI environment, you will want to make this variables known to the top level GUI as well. Both Windows and Mac OS X have interfaces to set environment variables. Some desktop environments running under X11 provide such an interface as well, or you can just add similar lines to ~/.xsession or ~/.xinitrc, depending on your setup.

So now that we have this configured, what can we add to this new file? Plenty of things. Let’s start by enhancing the $LOAD_PATH (also known as $:). My strategy here is to pop the current working directory off the end, add a few more directories, then restore it.

old_current = $LOAD_PATH.pop if $LOAD_PATH.last == '.'
%w(.ruby/lib ruby/lib .ruby ruby).each do |dir|
  $LOAD_PATH.unshift(File.expand_path("~/#{dir}"))
end
Dir[File.expand_path('~/ruby/*/lib')].each do |dir|
  $LOAD_PATH << dir
end
$LOAD_PATH << old_current if old_current
$LOAD_PATH.uniq!

I add a wide variety of directories here, feel free to adjust as you see fit. Note the addition of every directory matching ~/ruby/*/lib, which makes it easy to install new libraries in ~/ruby. This is something that would be tricky to do just by adjusting RUBYLIB.

Next, let’s load RubyGems. We can do this in such a way that it won’t fail on systems where it’s not installed.

begin
  require 'rubygems'
rescue LoadError
end

What else? How about always keeping good old Symbol#to_proc handy.

class Symbol
  def to_proc
    Proc.new { |*args| args.shift.__send__(self,*args) }
  end
end

One thing to be careful about is not letting your code grow dependent on this auto-loaded library. For example, if you add the above snippet and start doing pets.each(&:feed) all over the place, your code will break for other people without your library. I still define Symbol#to_proc because it’s handy for debug statements and quick scripts and it’s easy enough to avoid using where it’s important. But I avoid something more invasive like require 'active_support' because it’s harder to keep track of everything it provides. Use your own best judgement.

RESTFul Rails from Flex.

As part of the “MySpyder” project I am currently working on we want a Flex front-end to access a RESTFul Ruby on Rails service. You can read more on RESTFul and ActiveResource on David’s blog, on the “release notes” of Rails 1.2, PeepCode as an excellent screencast (not free) on the subject, and many other places.

In short using the RESTFul approach allows to expose and manipulate a Rails model via a predefined set of standard Http requests. For example we have an ActiveRecord named Watch which can be manipulated via the following requests:

command url
index # GET /watches.xml
show # GET /watches/1.xml
new # GET /watches/new
create # POST /watches.xml
update # PUT /watches/1.xml
delete # DELETE /watches/1.xml

This allows for standard CRUD operations. Note rest supports also custom operations and CRUD operations on nested resources (such as a has_many relationship). We won’t address them in the article, but I will certainly need them later in the project.

The Rails application can determined what format to return based on the content type or the extension of the url. We are only interested in xml for the moment.

Some of the advantages of a RESTFul Rails application are that it provides a standard way to organize your controllers, as you will see just in a moment because the controllers are standard most of the code can easily be generated, and because the URL to access the application are standard we can now provide some standard utility class to access a RESTFul server. Rails provides an ActiveResource client class, and I haven’t found one yet for Flex. So I started to write one which I will show here after. Now please contact me or add some comments to this blog if you find anything similar or if you want to help me out writing this class. Another cool feature of writing RESTFul Rails controllers is that you get an API for your application nearly for free. This is the main reason we went down that direction.

Assuming we have an ActiveRecord named Watch we can now generate a RESTFul Ruby on Rails controller issuing the following command

./script/generate scaffold_resource watch

Our server now supports RESTFul http requests.

Now wouldn’t it be nice if we could access the server data from Flex in the following manner:

import mx.rpc.AsyncToken;
import org.onrails.ActiveResourceClient;

var watches:ActiveResourceClient = new ActiveResourceClient();
watches.defineResource(“http://localhost:3000”, “watches”, resultHandler, faultHandler);

// Note that all the calls are performed in parallel and asynchronously.
watches.list()
watches.show(8)

// create
var data:XML =
www.picnik.com

10080

watches.create(data)

// update
data =
8
10080

data.frequency = 1440;
watches.update(data)

// delete
watches.deleteItem(8)

Now we can. I started to write the ActiveResourceClient actionscript class to allow this. It’s attached at the end of the article. Now, this is a first try I’ve created this morning. So please be critical and let’s improve it together, or even better if you have one or know one that’s way better please point me where I can get it.

To use the ActiveResourceClient just put the ActiveResourceClient.mxml file into the org.onrails folder in your Flex project. Note that you can provide a default result handler and fault handler or set one handler for each specific call, i.e. the watches.create returns an AsyncToken where a dedicated handler can be specified just to handle the result of the creation.

Download: ActiveResourceClient.mxml (renamed file to ActiveResourceClient.mxml)

Enjoy,
Daniel Wanja.

Welcome to MXNA readers.

OnRails.org has been added to Adobe’s xml news aggregator. You may wonder why a Ruby on Rails blog on Adobe’s aggregator and what my involvement with Flex is. Read my previous post to see why I believe Flex and Rails are a great match.

I used Flex since it was called Royale and develop 2 Flex application for customers that are currently in production. I am also currently working on three new projects that involve Flex, two off them are using Ruby on Rails as back end and one uses java. The java project is still using Flex 1.5. One is for Digital Seed and another is code named “MySpyder” for now and is just in it’s infancy.

I used to have a blog call f2ee.com (I gave away the domain name a while ago) named Flex+Flash Enterprise Edition which was solely focus on Flex. The only reminiscence left is on the wayback machine and two compiled demos, one PortfolioReader and some Scafolding Demo using Flex. I don’t even think I know where the source code of these demos is. Early 2005, I have also created with Lee Flex::OnRails (don’t use it, use WebORB) a framework to integrate Flex (and Flash) with Ruby using AMF4R.

More recently I open sourced the RailsLogVisualizer on rubyforge. This is a Flex a desktop application for OSX (I wish Apollo was out) with a embedded Ruby server (not Rails).

On this blog I wrote several entries related to Flash and Flex, like Integrating Flash with Ruby on Rails and Using WebORB to access ActiveRecords from a Flex application.

Next month I’ll be going to the 360flex conference and I’ll be blogging on the Flex Data Services related presentations.

Welcome!
Daniel Wanja.

Sneak Peek: Digital Seed: – an eLearning Application build Ruby on Rails and Flex.

Last year Sean and Greg asked us to join one of their venture as Ruby on Rails developers. Dolores joined as designer. Like Sean describes it “Digital Seed is a Flash and Ruby on Rails application that has been designed to allow learning and training companies to more easily deliver their “soft skills” training (leadership, management, communications, etc.) in a multimedia-rich online learning environment.”. This is a really fun project to work on. Sean put up a 10 minute screencast.

20070206-digital-seed.png

Certified Flex 2.0 Developer.

Last week I passed Adobe’s Flex 2 Developer Exam. Now what’s that got to with Rails. Like you may have seen in my previous post I like both technologies, Flex and Ruby on Rails, and I see the strength of both coming together and allowing to build some really cool applications. Now WebORB for Ruby on Rails will play a big element in tying both together. WebORB is not the only way to build a Flex app on top of a Ruby on Rails server, but it provides an efficient mechanism to transfer data between the UI and the server. Beginning of 2005 with Lee we wrote Flex::OnRails, a now “deprecated” (as in don’t even try to use it) framework, that was build on top of AMF4R. At that time combining Flex and Rails was an odd match, due to the pure enterprise nature of Flex with it’s very high price sticker. Now that Flex is free, I can see many projects benefiting from integrating both. It is true that many web sites don’t need a Rich User interfaces that go beyond what can be achieve with javascript. There are many javascript based websites that are incredible. See http://www.fluxiom.com/ or http://wufoo.com/ as two refined examples. However with Flex it’s often faster to build an application than with html and javascript, the applications often perform better, are easier to skin for a developer, the code is more readable and can support very large projects. Don’t take me wrong, I love the Prototype library and Scriptaculous is really cool, and I will do many more “pure” Ruby on Rails projects, but at least now there is a serious alternative that I will consider in many scenarios.

Now before you ask why did I even bother doing a certification, let me answer it. The first reason is that it forces me to read and study material that I would never have the patience to read otherwise as there is always too many cool things to try out. Now everyone has it’s own style of learning. I started Rails by reading all the rdoc that was available and I also love to read the source code. The second reasons is marketing, and this worked really well for me in the past and opened several doors. Personally, I wouldn’t value a developer by it’s certification but rather by the projects he worked on, the code he writes and it’s personality.

I haven’t found much information out there on the Flex certification which is pretty new . The Exam Preparation Guide by Adobe provides an overview and there is a more detailed version on the net which is not the official one. I found lot’s of information in Adobe’s online documentation and in the Flex 2, Training from the source book.

So be ready to hear a little more on Flex and Rails on this blog.

The Camping Episode – Ruby on Rails Podcast

Three interviews with developers who use why the lucky stiff’s Camping framework.
See also

The Camping Episode – Ruby on Rails Podcast

Three interviews with developers who use why the lucky stiff’s Camping framework.
See also

RailsConf 2007 registration is open!

UPDATED: REGISTER NOW!

I just received notification that my proposal for a talk at RailsConf was declined. The subject was of course, “Flex On Rails – Enterprise Data Manipulation.”. I hope that my friend Tony which made a proposal on a similar subject has been accepted. He is an excellent teacher. In addition the notification indicated that the registration starts tomorrow. So get ready!

New Rails Group in Seattle

For those in or near Seattle you might want to check out the new Rails group that is starting this month.  It is sponsored by Engine Yard and my friend’s company, Biego.  The first meeting is February 13th at 6pm at the Greenlake Public Library.  Too bad it wasn’t last week when I was in Seattle for a few days, I would have liked to seen what the Ruby community is like there.

Slicehost made us rich!

Actually, I guess they made us less poor.  Last month a bunch of our referrals finally paid off, saving us 70% of our usual monthly fee!  Thanks go to Kevin, Richard, Marty, John, Christopher, Brandon, Zachary, Piotr, and Jesse!

Why haven’t we written much about Slicehost in the 6 months we’ve been hosting on them?  Because it just works.  We just set up our apps and let them run.

If you’d like to be in our next thank you note, use this link when signing up for your slice.

Thanks again, referrals and Slicehost.

RailsConf registration starts 1st week of Februrary. So get ready!

The conference Wiki indicates that the registration starts the first week of February. Chad just notified the community that it’s coming soon. I speculate the registration opens tomorrow, February 1st. Rumored to be around $800.- and having more seats than the 700 of last year, it may take a little longer to sell the conference out this time. Let’s see. In any case get ready!

Does a good idea make a good business?

On top of our Ruby on Rails consulting work we would like to create a small internet “service” business. Something like time.onrails.org but more fleshed out and supporting paying customers. We are bringing on board Solomon White, which is an awesome Ruby on Rails developers, to help out. So the other day we met and threw out some ideas of project we would consider doing. I think we came with a bunch of great ideas that each on their own could support a nice business or at least would be fun to develop. Often the feeling is that sharing these ideas would give away the “magic” ingredients that would make the new venture a success, that competition would outrun us and they will be first and take the whole market. I don’t believe so. A very close friend created a spectacular Java/.Net integration framework. He is adamant about not revealing too much on how he created it or even that he created it. The result is that potential customers don’t “just” find him as they don’t know that a solution to their problem is out there, and he must convince them really hard that he has the solution, and sometimes that they have a problem. In other scenarios a ‘surprise’ announcement, like Apple masters so well, has certainly a great impact as that creates lot’s of buzz on the net and in the news. The reality is that we don’t have Apples audience and no one is expecting a ‘surprise’ from us. I don’t think that they are not many great ideas worth keeping secret Rather find a problem or need and make sure you create an awesome solution addressing it. While you create it, talk about it, spread the word, gather feedback, talk about the technical challenges you encounter, feel the interest that’s out there. Then deliver. And deliver something exceptional …sounds familiar? Well that concept is not invented here, but if we shine at taking one of “our” ideas, and providing an exceptional implementation I believe we can attract many users and create a nice business out of it.

So the steps in the process becomes something like this:

  1. Investigate ideas (that’s where we are at)
    1. Choose idea.
    2. Define project
    3. Implement and spread the word.
    4. Go live
    5. Adapt and Improve

Currently we are in the “investigation” phase for several of these ideas. In other words we are coding and having fun and testing out different things. So here is the list of our killers ideas (in no specific order):

RailsLogVisualer plug-in: Realtime and aggregated log visualization of your Rails application. At the end of last year I wrote an offline Rails Log Visualizer. It’s pretty basic but provides some interesting information about the different applications we have in production. While writing it I realized that it would not be too difficult to have a plugin that would collect and aggregate request data and be able to provide information on the specific controllers and actions of the application. Of course it would require to support clusters of Rails applications. This plugin would provide a nice drill-down approach to the log data analysis which differs from a more traditional log analysis approach. For now, check out Geoffrey’s article on how to add Rails support to Mint for a nice way to analyze your log data on a deployed server.

ScrumPlan: An Agile Project management tool. I still do tons of enterprise work, and I really like how Scrum brings teams together. Scrum is very simple and a spreadsheet can be sufficient to get started, but I see the need for a simple dedicated tool to support the different activities that is simpler, more efficient and elegant than the existing tools out there. Lee is not too hot on this idea as we don’t use Scrum on our small projects.

FlexTester: An automation/regression tool for Flex. A large part of this testing tools would be in Flex, but the tool would have a server side part that is written in Ruby on Rails to keeps track of tests runs, to drive continuous integration and so forth. Flex is not directly related to Rails but I also do a lot of Flex work. I just think it’s a very nice way to create an UI, although in many case RJS does the trick as nicely and is “more” conventional. Flex is appropriate for enterprise applications (with many screens, many developers, lots’ of functionality) and Adobe just added some framework level way to record and playback user events (see the mx.automation package). There is currently one very expensive tool out there to create regression tests for Flex. Another more affordable one would be welcome. I started playing with the mx.automation framework and I am evaluating the effort implementing such a tool.

TimeOnRails 2: We have several hundred registered users (858 today) for time on rails and many use it on a daily basis. We received great feedback and also improvement requests. We use it our-selves on a daily basis and see many ways we want to improve and make it even more useful, especially on projects with multiple team members. Rather than just fixing the current code based which was implemented during the pre-RESTFull area, we want to rewrite it from the ground up. Note if we don’t select that idea, I will need to fix promptly several small issues on time.onrails.org.

RailsCloud: Rails hosting on a cloud. Ways to deploy or scale you Rails environment at the click of a button…This would leverage Amazon’s EC2.

S3Backup: Backup to S3 with a twist!

MySyder: The last year we worked in the eCommerce field. It’s pretty amazing what’s going on in this field, and there is the need to provide better tools for vendor and online stores. As part of “investigating” this idea we defined a subset of functionality related to “watching specific html pages” that we can turn into an online service or product by it’s self.

As you see we’ve got many ideas. I like Solomon’s way of looking at these ideas…“Which one we do first?” … More on that in the future.