Integrating Flex and Ruby On Rails
Integrating Flex and Ruby On Rails
Note: This article was created based on Flex 2. Minor changes in the description and code may be necessary before it can be applied to Flex 3. In this article you will learn how to integrate Flex 2 with Ruby on Rails and a MySQL database by building a simple issue tracker application. By following the steps in this tutorial, you will also learn how to add functionality to the application, such as adding a new bug to the database, reading existing bugs, updating a bug, and deleting a bug. Prerequisite knowledge: Basic understanding of ActionScript, MXML, and Flex Builder.
Why Rails? When using Flex you have several options to choose from for back-end server software. So why might you want to choose Rails? Ruby on Rails, like Flex, is a well thought out, elegantly simple framework. As you will see, Rails uses code generation and metaprogramming to make it incredibly easy to integrate with a database using almost no SQL code. Furthermore, when you use Rails, you also get to use Ruby, a programming language that is both extremely powerful and easy to use. Using Flex and Ruby on Rails, you will be able to get more done with less code. Flex + Rails + Ruby = RIA Nirvana. Building the user interface To get started, you'll create the user interface for displaying the data. Open Flex Builder and go to File > New > Flex Application to create a new Project called ex_issuetracker. Once the project has been created, open ex_issuetracker.mxml and add the following code: <?xml version="1.0" encoding="utf-8"?> <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute"> <mx:Script> <![CDATA[ [Bindable] private var statusArray:Array = ["Opened", "Assigned", "Closed"]; [Bindable] private var priorityArray:Array = ["Blocker", "Critical", "Major", "Minor", "Trivial"]; ]]> </mx:Script> <mx:VDividedBox x="0" y="0" height="100%" width="100%">
1
<mx:Panel width="100%" height="376" layout="absolute" title="Create/Update Bugs"> <mx:Form x="10" y="10" width="930" height="280"> <mx:FormItem label="Reported by"> <mx:TextInput width="220" id="reportedby" text="{bugs_dg.selectedItem.reportedby}"/> </mx:FormItem> <mx:FormItem label="Assigned to"> <mx:TextInput width="220" id="assignedto" text="{bugs_dg.selectedItem.assignedto}"/> </mx:FormItem> <mx:FormItem label="Description"> <mx:TextArea width="336" height="111" id="description" text="{bugs_dg.selectedItem.description}"/> </mx:FormItem> <mx:FormItem label="Status" width="287"> <mx:ComboBox width="199" id="status" selectedIndex="{statusArray.indexOf(bugs_dg.selectedItem.status)}"> <mx:dataProvider> {statusArray} </mx:dataProvider> </mx:ComboBox>h </mx:FormItem> <mx:FormItem label="Priority">
3
Now that you've coded the interface, the next step is to set up your Rails application. First, you need to create a new database. This tutorial uses MySQL, but Rails is capable of supporting many other databases, too. Open your MySQL Command Line Client and enter the following line: CREATE ex_issue_tracker_development That is all the SQL you are going to need to write. Rails will take care of the rest. To create your Rails application, open up a command-line window and change the directory to the location that you would like to use for your application. I generally use C: \Dev. Once you're in your desired location on your server, enter the following line: rails issue_tracker This command generates all of the folders and les that you will need for your Rails application. Part of the power of Rails is that it promotes consistency across projects by ensuring that all Rails applications have the same structure. Next, create the model for this application. In Rails, the model is the code that wraps a table in your database. To create your model, enter the following line: cd issue_tracker To change the directory to your Rails app. Next, enter the following line: ruby script/generate model bug Finally, you'll create the controller. The controller contains the logic for interacting between the view (in this case Flex) and the model. To create your controller enter the following line: ruby script/generate controller bugs Now, inside your Rails application folder, go to app > controllers. You will see the bugs_controller.rb le that you just generated. Open this le and add the following code:
The command-line window Figure 1. The command-line window Finally, set up your Rails app to boot up the server. Ruby comes with its own handy server called WEBrick. To start WEBrick go to the command line and enter: ruby script/server Note that the server defaults to running on port 3000. This will be important in the next section. That's it. Your Rails app is all ready. If you open up an Internet browser and type http://localhost:3000 you will see the Rails welcome page.
Now that you've got your Flex interface, your Rails app, and your database all set up, the next step is to get Flex talking with Rails. Fortunately, this is really easy. You are going to be using the HTTPService to call the create, list, update, and delete methods that you added to the bugs_controller.rb le in your Rails application. Add the following code to your Flex application: <mx:HTTPService id="listBugs" url="http://localhost:3000/bugs/list" useProxy="false" method="GET"/>
<mx:HTTPService id="updateBug" url="http://localhost:3000/bugs/update" useProxy="false" method="POST" result="listBugs.send()"/>
<mx:HTTPService id="deleteBug" url="http://localhost:3000/bugs/delete" useProxy="false" method="POST" result="listBugs.send()"/>
<mx:HTTPService id="createBug" url="http://localhost:3000/bugs/create" useProxy="false" method="POST" result="listBugs.send()" contentType="application/xml"> <mx:request xmlns=""> <bug> <reportedby>{reportedby.text}</reportedby> <assignedto>{assignedto.text}</assignedto> <description>{description.text}</description> <status>{status.text}</status> <priority>{priority.text}</priority> </bug> </mx:request>
</mx:HTTPService> Each of the four HTTPServices that you just added calls one of the methods in your Rails application. Notice that the url attribute in each HTTPService follows the structure: http:// <server address>/<controller name>/<method name>. Note: When you are ready to deploy your application, change these URLs from absolute to relative (for instance, url="http://localhost:3000/bugs/list" becomes url="bugs/list")and move the SWF les and HTML les that are generated by Flex into the public folder in your Rails app. Next, edit the Clear, Update, and Create buttons that are under your form to look like the following: <mx:Button label="Clear" click="clearForm()"/> <mx:Button label="Update" click="sendBugUpdate(); clearForm()"/> <mx:Button label="Create" click="createBug.send(); clearForm()"/> Then, edit the Delete button under your DataGrid component to look like the following: <mx:Button label="Delete" click="deleteBug.send({id:bugs_dg.selectedItem.id}); "/>
9
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" creationComplete="listBugs.send()"> Lastly, add the following two functions inside the <mx:Script> block, just below the two arrays: private function clearForm():void { reportedby.text = "" assignedto.text = ""; description.text = ""; status.selectedIndex = 0; priority.selectedIndex = 0; } private function sendBugUpdate():void {
var bugUpdate:Object = new Object(); bugUpdate['id'] = bugs_dg.selectedItem.id; bugUpdate['bug[reportedby]'] = reportedby.text; bugUpdate['bug[assignedto]'] = assignedto.text; bugUpdate['bug[description]'] = description.text; bugUpdate['bug[status]'] = status.text; bugUpdate['bug[priority]'] = priority.text; updateBug.send(bugUpdate); }
That's it. With surprisingly little code, your issue tracker is ready to roll. You now have an interface and a back end that support basic CRUD operations. To test it out, click run inside Flex Builder. Once the app launches, ll in the form with some data for a new bug. Click the Create button and you will see a new entry appear in the datagrid. Add a few more bugs, and then close the application. Go back in to Flex Builder and click run again. This time, when the application launches, you will see the bugs that you already entered appear in the datagrid. You can now update these bugs, delete them, or create new bugs and your changes will automatically be persisted to your database.
10
Now that you know the basics of how to integrate Flex with Rails I encourage you to dive in deeper into Flex, Rails, and Ruby to see what is possible when you combine these technologies. Get a copy Flex Builder 2 and RadRails (both use Eclipse, so they work nicely together), and check out the Flex Quick Starts and the Flex 2 LiveDocs site to learn more about Flex. To learn more about Rails, take a look out the Howtos site and Rails API. If you want to get a better understanding of Ruby, there are two excellent books available online. One is the often strange, but highly entertaining why's (poignant) guide to Ruby, and the other is Programming Ruby: The Pragmatic Programmer's Guide. Also, be sure to sign up for the Ruby on Rails RIA Mailing list. Comments (2) * Crystal Shadow(May 11, 2008) Great article! For rails 2.0.2, there is a little bug : I can't create bugs. I had to comment the line 9 in the le issue_tracker/app/controllers/application.rb * Kevin Kohrt(July 15, 2008) Thanks for the quick demo. All the one line additions above imply they are special and have a specic purpose beyond boiler plate, but you are just telling us to insert some parameter of a certain type (e.g. a 'dataProvider'), without explaining why that particular type is needed at that particular location, and what and how it does the needful. So I think you could make a good write up even better by adding some more about 'why?', but I am grateful for what you have to date.
11