DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Last call! Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

  1. DZone
  2. Refcards
  3. Flexible Rails: Flex 3 on Rails 2
refcard cover
Refcard #009

Flexible Rails: Flex 3 on Rails 2

Flex UI on Ruby Web Apps

Provides an overview of Flex and Rails and how they can be used together to build a simple Flex+Rails application using XML over HTTPService.

Download Refcard
Free PDF for Easy Reference
refcard cover

Written By

author avatar Peter Armstrong
CEO, Ruboss Technology Corporation
Table of Contents
► About Flexible Rails ► Overview of Rails 2 ► Overview of Flex 3 ► Flex 3 and Rails 2 Together ► Installing Everything ► Building a Flex + Rails Application ► Resources
Section 1

About Flexible Rails

By Peter Armstrong

Simply put, Flex is the most productive way to build the UI of Rich Internet Applications, and Rails is a very productive way to rapidly build a database-backed CRUD application, thanks to ActiveRecord (the ORM layer of Rails) and thanks to the principles of Convention Over Configuration and DRY (Don't Repeat Yourself). This refcard shows you how to get started. It provides an overview of Flex and Rails, how they can be used together and then building a simple Flex + Rails application using XML over HTTPService to have the Flex client talk to a RESTful Rails server. Since we'll use RESTful Rails controllers, the Rails controller methods will also support the traditional HTML views.

Section 2

Overview of Rails 2

Rails provides a standard three-tier architecture (presentation tier, model tier, persistence tier) as well as a Model-View-Controller (MVC) architecture. As shown in Figure 1, Rails takes care of everything between the web server and the database.

Overview of Rails Diagram

Figure 1.

Figure 1: Rails provides a standard three-tier architecture (presentation tier, model tier, persistence tier) as well as a Model-View-Controller architecture.

The typical sequence is as follows:

  1. A user visits a particular URL in their web browser (makes an HTTP request).
  2. This request goes over the Internet to the web server in which Rails is running.
  3. That web server passes the request to the routing code in Rails, which triggers the appropriate controller method call based on the routes defined in config\routes.rb.
  4. The controller method is called. It communicates with various ActiveRecord models (which are persisted to and retrieved from a database of your choosing). The controller method can then do one of two things:
    1. Set some instance variables and allow a view template (a specially named .html.erb file, for example) to be used to produce HTML, XML, or JavaScript, which is sent to the browser.
    2. Bypass the view mechanism and do r endering directly via a call to the render method. This method can produce plain text (render :text => "foo"), XML (render :text => @task), and so on.
Section 3

Overview of Flex 3

In Flex 3, you write code in MXML (XML files with a .mxml extension; M for Macromedia) and ActionScript (text files with a .as extension) files and compile them into a SWF file, which runs in the Flash player. This SWF is referenced by an HTML file, so that when a user with a modern web browser loads the HTML file, it plays the Flash movie (prompting the user to download Flash 9 if it's not present). The SWF contained in the web page can interact with the web page it's contained in and with the server it was sent from.

Section 4

Flex 3 and Rails 2 Together

Flex and Rails can be used together with XML over HTTPService or with Action Message Format. The XML over HTTPService approach is shown in Figure 2 below.

Flex 3 and Rails 2 Together Diagram

Figure 2.

The AMF waters are a bit muddier: there are currently three ways that Flex can talk to Rails using AMF and RemoteObject:

  • RubyAMF
  • WebORB for Rails
  • BlazeDS (with Rails running on JRuby).

Hot Tip

Flash 9? Are you kidding me?

The reference to Flash 9 earlier may have set off alarm bells in your head: Isn't Flash 9 somewhat new? How many people will be able to run my app? Well, while not everyone has Flash 9, most do: according to http://www.adobe.com/products/player_census/flashplayer/version_penetration.html Flash 9 has reached near ubiquity: 97.3% in US/Canada, 96.5% in Europe and 98.0% in Japan. This is better than Windows.

Section 5

Installing Everything

To get started, various software packages need to be installed. The full instructions can be found in chapter 2 of Flexible Rails (Manning Publications). Here's what is needed:

  1. Ruby 1.8.6
  2. RubyGems 1.0.0 (or higher)
  3. Rails. 2.0.2 (or higher)
  4. Flex Builder 3
  5. SQLite
  6. The sqlite3 gem, installed by running this command: C:\>gem install sqlite3-ruby
Resource URL Notes
RubyonRails http://rubyonrails.org/down  
HiveLogic http://hivelogic.com/articles/2008/02/ruby-rails-leopard  
SQLite http://www.sqlite.org/download.html On Windows, download sqlite-3_5_5.zip or higher and sqlitedll-3_5_5.zip or higher, and unzip both of them into C:\WINDOWS\system32
Section 6

Building a Flex + Rails Application

The world doesn't need Yet Another Todo List, but let's build one. Unlike most Rails tutorials, we will assume you are using Windows. (Rails has "crossed the chasm", so this is now becoming the correct assumption.)

Open a command prompt or Terminal window and run the following commands:

1
C:\>rails todo

This installs the SQLite3 gem and then creates a new Rails application which by default uses the SQLite database. (The default in Rails 2.0.1 and below was MySQL.)

Next, create a couple of directories:

3
1
C:\>cd todo
2
C:\todo>mkdir app\flex
3
C:\todo>mkdir public\bin

Next, switch to Flex Builder 3 and create the new Flex project:

  1. Do File > New > Flex Project...
  2. Choose to create a new project named Todo in c:\todo
  3. Leave its type set to "Web application" and its "Application server type" set to None and click Next
  4. Set the Output folder of the Flex project to public\bin and click Next
  5. Set the "Main source folder" to app\flex, leave the "Main application file" as Todo.mxml and set the output folder to http://localhost:3000/bin and click Finish. Your new Flex project will be created. (Note that public isn't part of the path since it's the root; 3000 is the default port for the server).

Hot Tip

We are using app\flex as the root of all our Flex code,in larger team environments it's advisable to create a Flex project as a sibling of the Rails app (say, c:\todoclient) and set its output folder to go inside c:\todo\public\bin. This way, different team members can use different IDEs for the client and server projects: for example, Aptana and Flex Builder are both Eclipse-based, and interesting things can happen when you nest projects.

Next, let's create a new Task resource using the now-RESTful scaffold command.

1
1
C:\todo>ruby script\generate scaffold Task name:string

Here we are creating a Task that has a name attribute, which is a string. Running this command generates the various Rails files, including the model, helper, controller, view templates, tests and database migration. We're going to make the simplest Todo list in history: Tasks have names, and nothing else. Furthermore, there are no users even, just a global list of tasks.

The Task model looks like this:

2
1
class Task < ActiveRecord::Base
2
end

Because the Task model extends (with <) ActiveRecord::Base, it can be mapped to the equivalent database tables. Because we also created the controllers and views with the script\generate scaffold command and ensured that we specified all the fields, we can use a prebuilt web interface to Create, Read, Update, and Delete (CRUD) them.

The CreateTasks migration that was created (in db\migrate\001_create_tasks.rb) looks like this:

11
1
class CreateTasks < ActiveRecord::Migration
2
def self.up
3
create_table :tasks do |t|
4
t.string :name
5
t.timestamps
6
end
7
end
8
def self.down
9
drop_table :tasks
10
end
11
end
CreateTasks Class Extends ActiveRecord::Migration
Up method Creates a new tasks table with the create_table method call, which takes a block that does the work
Down method Deletes it with the drop_table call

In the up method, we specify the data types of each new column, such as string in our case, or boolean, integer or text. These are then mapped to the equivalent database data types: for example, boolean becomes a tinyint(1) in MySQL. The timestamps call adds two columns: created_at and updated_at, which Rails treats specially, ensuring that they're automatically set. This is often a good thing to have, so we'll leave them there even though they won't be needed in this build.

The TasksController (in app\controllers\tasks_controller.rb) looks like this:

79
1
class TasksController < ApplicationController
2
# GET /tasks
3
# GET /tasks.xml
4
def index
5
@tasks = Task.find(:all)
6
respond_to do format|
7
format.html # index.html.erb
8
format.xml { render :xml => @tasks }
9
end
10
end
11
# GET /tasks/1
12
# GET /tasks/1.xml
13
def show
14
@task = Task.find(params[:id])
15
respond_to do |format|
16
for
17
mat.html # show.html.erb
18
format.xml { render :xml => @task }
19
end
20
end
21
# GET /tasks/new
22
# GET /tasks/new.xml
23
def new
24
@task = Task.new
25
respond_to do |format|
26
for
27
mat.html # new.html.erb
28
format.xml { render :xml => @task }
29
end
30
end
31
# GET /tasks/1/edit
32
def edit
33
@task = Task.find(params[:id])
34
end
35
# POST /tasks
36
# POST /tasks.xml
37
def cr
38
eate
39
@task = Task.new(params[:task])
40
respond_to do |format|
41
if @task.save
42
flash[:notice] = 'Task was successfully created.'
43
format.html { redirect_to(@task) }
44
format.xml { render :xml => @task,
45
:status => :created, :location => @task }
46
else
47
format.html { render :action => "new" }
48
format.xml { render :xml => @task.errors,
49
:status => :unprocessable_entity }
50
end
51
end
52
end
53
# PUT /tasks/1
54
# PUT /tasks/1.xml
55
def update
56
@task = Task.find(params[:id])
57
respond_to do |format|
58
if @task.update_attributes(params[:task])
59
flash[:notice] = 'Task was successfully updated.'
60
format.html { redirect_to(@task) }
61
format.xml { head :ok }
62
else
63
format.html { render :action => "edit" }
64
format.xml { render :xml => @task.errors,
65
:status => :unprocessable_entity }
66
end
67
end
68
end
69
# DELETE /tasks/1
70
# DELETE /tasks/1.xml
71
def destroy
72
@task = Task.find(params[:id])
73
@task.destroy
74
respond_to do |format|
75
format.html { redirect_to(tasks_url) }
76
format.xml { head :ok }
77
end
78
end
79
end|

This new controller which was generated for us contains the seven RESTful controller methods, which are explained in the following table (inspired by David Heinemeier Hansson's Discovering a World of Resources on Rails presentation - media.rubyonrails.org/presentations/worldofresources.pdf, slide 7,as well as the table on p. 410 of Agile Web Development with Rails, 2nd ed. (The Pragmatic Programmers), and the tables in Geoffrey Grosenbach's REST cheat sheet http://topfunky.com/clients/peepcode/REST-cheatsheet.pdf):

# Method Sample URL paths Pretend HTTP Method Actual HTTP Method Corres- ponding CRUD Method Corres- ponding SQL Method
1 index /tasks
/tasks.xml
GET GET READ SELECT
2 show /tasks/1
/tasks/1.xml
GET GET READ SELECT
3 new /tasks/new
/tasks/new.xml
GET GET - -
4 edit /tasks/1/edit GET GET READ SELECT
5 create /tasks
/tasks.xml
POST POST CREATE INSERT
6 update /tasks/1
/tasks/1.xml
PUT POST UPDATE UPDATE
7 destroy /tasks/1
/tasks/1.xml
DELETE POST DELETE DELETE

Table 1: The seven standard RESTful controller methods

Hot Tip

What's REST?

REST (Representational State Transfer) is a way of building web services that focuses on simplicity and an architecture style that is of the web. This can be described as a Resource Oriented Architecture (ROA); see RESTful Web Services published by O'Reilly Media for details. Briefly, the reason to use a RESTful design in Rails is that it helps us organize our controllers better, forces us to think harder about our domain, and gives us a nice API for free.

Next, we run the new migration that was created (CreateTasks) when we ran the scaffold command:

1
1
C:\todo>rake db:migrate

At this point we run the server:

1
1
C:\todo>ruby script\server

and play with creating, editing and deleting tasks.

  1. Go to http://localhost:3000/tasks/new to see an empty task list.
  2. Click the New link to go to http://localhost:3000/tasks/new.
  3. Create a new Task with a name of "drink coffee" and click Create.
  4. Go back to http://localhost:3000/tasks/new to see the task list with the new "drink coffee" task present.

Now, let's do something interesting and hook this up to Flex. Currently, the Todo.mxml file looks like this:

<?xml version="1.0" encoding="utf-8"?> <mx:Application xmlns:mx="http://www.adobe.com/ 2006/mxml" layout="absolute"> </mx:Application>

The top-level tag is mx:Application; the root of a Flex application is always an Application. The mx: part identifies the XML namespace that the Application component is from. By default, an Application uses an absolute layout, where you specify the x,y of each top level container and component.

What we want to build is the following application:

The Simple Todo Flex Application

Figure 3: The Simple Todo Flex Application

We want the ability to create new tasks, delete tasks and rename them inline in the list. Furthermore, we want to do this in the least amount of code possible. Normally, I'd build this iteratively; but we'll build it all at once. Modify the Todo.mxml file to look like this:

​x
1
​
2
<?xml version="1.0" encoding="utf-8"?>
3
<mx:Application
4
xmlns:mx="http://www.adobe.com/2006/mxml"
5
width="100%" height="100%" layout="vertical"
6
backgroundGradientColors="[#000000, #CCCCCC]"
7
creationComplete="svcTasksList.send()">
8
<mx:Script>
9
<![CDATA[
10
import mx.events.ListEvent;
11
import mx.controls.Alert;
12
import mx.rpc.events.ResultEvent;
13
private function createTask():void {
14
svcTasksCreate.send();
15
}
16
private function deleteTask(task:XML):void {
17
svcTasksDestroy.url = "/tasks/" + task.id + ".xml";
18
svcTasksDestroy.send({_method: "DELETE"});
19
}
20
private function updateSelectedTask(event:ListEvent): void {
21
var itemEditor:TextInput =
22
TextInput(event.currentTarget.itemEditorInstance);
23
var selectedTask:XML = XML(event.itemRenderer.data);
24
if (selectedTask.name == itemEditor.text) return;
25
var params:Object = new Object();
26
params['task[name]'] = itemEditor.text;
27
params['_method'] = "PUT";
28
svcTasksUpdate.url = "/tasks/"+ selectedTask.id +".xml";
29
svcTasksUpdate.send(params);
30
}
31
private function listTasks():void {
32
svcTasksList.send();
33
}
34
]]>
35
</mx:Script>
36
<mx:HTTPService id="svcTasksCreate" url="/tasks.xml"
37
contentType="application/xml" resultFormat="e4x"
38
method="POST" result="listTasks()">
39
<mx:request>
40
<task><name>{newTaskTI.text}</name></task>
41
</mx:request>
42
</mx:HTTPService>
43
<mx:HTTPService id="svcTasksList" url="/tasks.xml"
44
resultFormat="e4x" method="POST"/>
45
<mx:HTTPService id="svcTasksUpdate" resultFormat="e4x"
46
method="POST" result="listTasks()"/>
47
<mx:HTTPService id="svcTasksDestroy" resultFormat="e4x"
48
method="POST" result="listTasks()"/>
49
<mx:XMLListCollection id="tasksXLC"
50
source="{XMLList(svcTasksList.lastResult.children())}"/>
51
<mx:Panel title="Simple Todo" width="100%" height="100%">
52
<mx:HBox width="100%" paddingLeft="5"
53
paddingRight="5"
54
paddingTop="5">
55
<mx:Label text="New Task"/>
56
<mx:TextInput id="newTaskTI" width="100%"
57
enter="createTask()"/>
58
<mx:Button label="Create" click="createTask()"/>
59
</mx:HBox>
60
<mx:List id="taskList" width="100%" height="100%"
61
editable="true" labelField="name"
62
dataProvider="{tasksXLC}"
63
itemEditEnd="updateSelectedTask(event)"/>
64
<mx:ControlBar width="100%" horizontalAlign="center">
65
<mx:Button label="Delete" width="100%" height="30"
66
enabled="{taskList.selectedItem != null}"
67
click="deleteTask(XML(taskList.selectedItem))"/>
68
</mx:ControlBar>
69
</mx:Panel>
70
</mx:Application>
71
​
72
​

This is a complete Flex application in 67 lines of code! Compile and run the application by clicking the green "play" button: you will see the screen shown in Figure 3.

A Quick Highlight Tour of this Code:

1

We use a vertical layout to make the components flow vertically. Other choices are horizontal (for horizontal flow) and absolute (which we saw before). The backgroundGradientColors specify the start and end of the gradient fill for the background.

2

We define a HTTPService svcTasksList, which does a GET to /tasks.xml (thus triggering the index action of the TasksController) and specifies a resultFormat of e4x so the result of the service can be handled with the new E4X XML API. We then take the lastResult of this service, which is an XML document, get its children (which is an XMLList of the tasks), and make this be the source of an XMLListCollection called tasksXLC. We do this with a binding to the source attribute. Similarly, we define svcTasksCreate, svcTasksUpdate and svcTasksDestroy to be used for the other CRUD operations.

3

We can pass data to Rails via data bindings using curly braces {} inside XML (as shown in svcTaskCreate) or by sending form parameters that Rails would be expecting (as shown in the updateSelectedTask method).

4

For svcTasksUpdate and svcTasksDestroy we are not setting the url property statically, but instead dynamically setting it to include the id of the task we are updating or destroying.

5

A hack: you can't send HTTP PUT or DELETE from the Flash player in a web browser, so we need to fake it. Luckily, since you can't send PUT or DELETE from HTML in a web browser either, Rails already has a hack in place we just need to know how to use it. Rails will look for a _method parameter in its params hash and, if there is one, use it instead of the actual HTTP method. So, if we do a form POST with a _method of PUT, Rails will pretend we sent an HTTP PUT. (If you're thinking that it's ironic that at the core of a "cleaner" architecture is a giant hack, well, you're not alone.) This _method can be added to a params Object (params['_method'] = "PUT";) or to an anonymous object (svcTasksDestroy.send({_method: "DELETE"});) If you're new to Flex, {} can be used for both anonymous object creation and for data binding. Think of an anonymous object like a hash in Ruby.

Section 7

Resources

Organization URL Information
Manning Publications http://www.manning.com/armstrong Book: Flexible Rails provides a code-focused, iterative tutorial introduction to using Flex with Rails.
http://www.manning.com/armstrong2 Book: Enterprise Flexible Rails provides the definitive tutorial introduction to the Ruboss Framework.
Ruboss Technology Corporation http://www.ruboss.com The Ruboss Framework: The Open Source Framework Which Puts Flex On Rails. Ruboss taking the Flex + Rails combination further, making it even easier and more accessible to the Enterprise.

Like This Refcard? Read More From DZone

related article thumbnail

DZone Article

Ruby: Open A File, Write To It, And Close It In One Line
related article thumbnail

DZone Article

A Deep Dive Into Firmware Over the Air for IoT Devices
related article thumbnail

DZone Article

Agentic AI for Automated Application Security and Vulnerability Management
related article thumbnail

DZone Article

Ensuring Configuration Consistency Across Global Data Centers
related refcard thumbnail

Free DZone Refcard

Getting Started With Low-Code Development
related refcard thumbnail

Free DZone Refcard

JavaScript Test Automation Frameworks
related refcard thumbnail

Free DZone Refcard

Salesforce Application Design
related refcard thumbnail

Free DZone Refcard

E-Commerce Development Essentials

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends: