CONTENTS INCLUDE: N Flexible Rails: Flex 3 On Rails 2 N

2y ago
22 Views
2 Downloads
2.10 MB
6 Pages
Last View : 14d ago
Last Download : 3m ago
Upload by : Milo Davies
Transcription

www.dzone.comGet More Refcardz! Visit refcardz.com#9CONTENTS INCLUDE:nnnnnnAbout Flexible RailsOverview of Rails 2Overview of Flex 3Flex 3 and Rails 2 TogetherBuilding a Flex RailsApplicationHot Tips and more.Flexible Rails: Flex 3 on Rails 2By Peter ArmstrongThe typical sequence is as follows:ABOUT FLEXIBLE RAILS1. A user visits a particular URL in their web browser (makesan HTTP request).Simply put, Flex is the most productive way to build the UIof Rich Internet Applications, and Rails is a very productiveway to rapidly build a database-backed CRUD application,thanks to ActiveRecord (the ORM layer of Rails) and thanksto the principles of Convention Over Configuration andDRY (Don’t Repeat Yourself). This refcard shows you how toget started. It provides an overview of Flex and Rails, howthey can be used together and then building a simple Flex Rails application using XML over HTTPService to havethe Flex client talk to a RESTful Rails server. Since we’ll useRESTful Rails controllers, the Rails controller methods willalso support the traditional HTML views.2. This request goes over the Internet to the web server inwhich Rails is running.3. That web server passes the request to the routing code inRails, which triggers the appropriate controller method callbased on the routes defined in config\routes.rb.4. The controller method is called. It communicates withvarious ActiveRecord models (which are persisted to andretrieved from a database of your choosing). The controllermethod can then do one of two things:1.OVERVIEW OF RAILS 22. Bypass the view mechanism and do renderingdirectly via a call to the render method. This methodcan produce plain text (render :text "foo"), XML(render :text @task), and so on.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 ofeverything between the web server and the database.OVERVIEW OF FLEX 3ClientWeb BrowserHTTP ScriptIn Flex 3, you write code in MXML (XML files with a .mxmlextension; M for Macromedia) and ActionScript (text files witha .as extension) files and compile them into a SWF file, whichruns in the Flash player. This SWF is referenced by an HTMLfile, so that when a user with a modern web browser loadsthe HTML file, it plays the Flash movie (prompting the userto download Flash 9 if it’s not present). The SWF contained inthe web page can interact with the web page it’s containedin and with the server it was sent from.InternetFlexible Rails: Flex 3 on Rails 2render :text, render ntroller(Controller)Set some instance variables and allow a viewtemplate (a specially named .html.erb file, forexample) to be used to produce HTML, XML, orJavaScript, which is sent to the browser.PresentationTierActionView(View)tech facts at your fingertipsGet More Refcardz(They’re free!)ActiveRecord(Model)Model TiernnnMethod Nameopen(method, url, async)onreadystatechangeMySQLPostgreSQLOracleDB2, etc.a URLopen a connection to(GET, POST, etc.)method HTTP verbinclude querystringurl url to open, mayasynchronous requestasync whether to onseHeaderadd a header to the HTTPtech facts atrequestyour fingertipsnsend the requestas request bodybody string to be usedfor the responsestop the XHR from listening(only populated after send()stage in lifecycle of responseis called)after(integer, only populatedThe HTTP return codeloaded state)response reaches theset afterJavaScript string (onlybody of response as ainteractive readyState)response reaches the(onlyas a XML document objectbody of the responsethe interactive readyState)set after response reachesread a response headernby nameGet an array of all responseheader namesnSubscribe Now for FREE!Refcardz.comFigure 1: Rails provides a standard three-tier architecture (presentation tier, model tier, persistence tier) as well as a Model-View-Controllerarchitecture.DZone, Inc.HotTipas callback (similar to onclick,assign a function objectevent model)onload, etc. in Parameters and DescriptionsAuthoritative contentDesigned for developersWritten by top expertsLatest tools & technologiesHot tips & examplesBonus content onlineNew issue every 1-2 weeks www.dzone.com

2Flexible Rails: Flex 3 on Rails 2tech facts at your fingertipsFLEX 3 AND RAILS 2 TOGETHERINSTALLING EVERYTHINGFlex and Rails can be used together with XML over HTTPServiceor with Action Message Format. The XML over HTTPServiceapproach is shown in Figure 2 below.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.6Web Browser with Flash Player 9WebPage2. RubyGems 1.0.0 (or higher)ClientFlex app (SWF)3. Rails. 2.0.2 (or higher)4. Flex Builder 35. SQLiterender :text, render :xmlHTTP ernet6. The sqlite3 gem, installed by running this command:C:\ gem install View(View)Model TierActiveRecord(Model)NotesOn Windows, downloadsqlite-3 5 5.zip or higherand sqlitedll-3 5 5.zip orhigher, and unzip both ofthem into C:\WINDOWS\system32BUILDING A FLEX RAILS APPLICATIONPersistenceTierThe world doesn’t need Yet Another Todo List, but let’s buildone. Unlike most Rails tutorials, we will assume you are usingWindows. (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:MySQL , PostgreSQLOracle, DB2, etc.Figure 2.C:\ rails todoThis installs the SQLite3 gem and then creates a new Rails application which by default uses the SQLite database. (The defaultin Rails 2.0.1 and below was MySQL.)The AMF waters are a bit muddier: there are currently threeways that Flex can talk to Rails using AMF and RemoteObject:nRubyAMFnWebORB for RailsC:\ cd todonBlazeDS (with Rails running on JRuby).C:\todo mkdir app\flexNext, create a couple of directories:C:\todo mkdir public\binFYINext, switch to Flex Builder 3 and create the new Flex project:Flash 9? Are you kidding me?1. Do File New Flex Project.The reference to Flash 9 earlier may have set off2. Choose to create a new project named Todo in c:\todoalarm bells in your head: “Isn’t Flash 9 somewhat3. Leave its type set to “Web application” and its “Applicationserver type” set to None and click Nextnew? How many people will be able to run my app?” Well,while not everyone has Flash 9, most do: according to http://4. Set the Output folder of the Flex project to public\bin andclick Nextwww.adobe.com/products/player census/flashplayer/5. Set the “Main source folder” to app\flex, leave the “Mainapplication file” as Todo.mxml and set the output folderto http://localhost:3000/bin and click Finish. Your new Flexproject will be created. (Note that public isn’t part of thepath since it’s the root; 3000 is the default port for the server).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.DZone, Inc. www.dzone.com

3Flexible Rails: Flex 3 on Rails 2tech facts at your fingertipsHotTipThe TasksController (in app\controllers\tasks controller.rb)looks like this:We are using app\flex as the root of all ourFlex code—in larger team environments it’sadvisable to create a Flex project as a siblingof the Rails app (say, c:\todoclient) and setits output folder to go inside c:\todo\public\bin. This way, different team members can usedifferent IDEs for the client and server projects:for example, Aptana and Flex Builder are bothEclipse-based, and interesting things canhappen when you nest projects.class TasksController ApplicationController# GET /tasks# GET /tasks.xmldef index@tasks Task.find(:all)format.html # index.html.erbformat.xml { render :xml @tasks }Building a Flex Rails Application, continuedendendNext, let’s create a new Task resource using the now-RESTfulscaffold command.# GET /tasks/1# GET /tasks/1.xmldef showC:\todo ruby script\generate scaffold Task name:string@task Task.find(params[:id])Here we are creating a Task that has a name attribute, whichis a string. Running this command generates the various Railsfiles, including the model, helper, controller, view templates,tests and database migration. We’re going to make the simplestTodo list in history: Tasks have names, and nothing else. Furthermore, there are no users even, just a global list of tasks.respond to do format format.html # show.html.erbformat.xml { render :xml @task }endendThe Task model looks like this:# GET /tasks/newclass Task ActiveRecord::Baseend# GET /tasks/new.xmldef newBecause the Task model extends (with ) ActiveRecord::Base, itcan be mapped to the equivalent database tables. Because wealso created the controllers and views with the script\generatescaffold command and ensured that we specified all the fields,we can use a prebuilt web interface to Create, Read, Update,and Delete (CRUD) them.@task Task.newrespond to do format format.html # new.html.erbformat.xml { render :xml @task }endendThe CreateTasks migration that was created (in db\migrate\001create tasks.rb) looks like this:# GET /tasks/1/editdef editclass CreateTasks ActiveRecord::Migrationdef self.upcreate table :tasks do t t.string :namet.timestampsendenddef self.downdrop table :tasksendend@task Task.find(params[:id])end# POST /tasks# POST /tasks.xmldef create@task Task.new(params[:task])respond to do format if @task.saveflash[:notice] 'Task was successfully created.'format.html { redirect to(@task) }format.xml { render :xml @task,CreateTasks ClassExtends ActiveRecord::MigrationUp methodCreates a new tasks table with the create table method call,which takes a block that does the workDown methodrespond to do format :status :created, :location @task }elseDeletes it with the drop table callformat.html { render :action "new" }format.xml { render :xml @task.errors,In the up method, we specify the data types of each newcolumn, 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. Thetimestamps call adds two columns: created at and updatedat, which Rails treats specially, ensuring that they’re automaticallyset. This is often a good thing to have, so we’ll leave themthere even though they won’t be needed in this build.DZone, Inc.:status :unprocessable entity }endendend# PUT /tasks/1# PUT /tasks/1.xml www.dzone.com

4Flexible Rails: Flex 3 on Rails 2tech facts at your fingertipsBuilding a Flex Rails Application, continuedWhat’s REST?REST (Representational State Transfer) is away of building web services that focuses onsimplicity 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 Mediafor details. Briefly, the reason to use a RESTful design in Railsis that it helps us organize our controllers better, forcesus to think harder about our domain, and gives us a niceAPI for free.def updateFYI@task Task.find(params[:id])respond to do format if @task.update attributes(params[:task])flash[:notice] 'Task was successfully updated.'format.html { redirect to(@task) }format.xml { head :ok }elseformat.html { render :action "edit" }format.xml { render :xml @task.errors,:status :unprocessable entity }endNext, we run the new migration that was created (CreateTasks)when we ran the scaffold command:endendC:\todo rake db:migrate# DELETE /tasks/1At this point we run the server:# DELETE /tasks/1.xmlC:\todo ruby script\serverdef destroy@task Task.find(params[:id])@task.destroyrespond to do format and play with creating, editing and deleting tasks.1. Go to http://localhost:3000/tasks to see an empty task list.format.html { redirect to(tasks url) }2. Click the New link to go to http://localhost:3000/tasks/new.format.xml { head :ok }3. Create a new Task with a name of “drink coffee” andclick Create.endend4. Go back to http://localhost:3000/tasks to see the task listwith the new “drink coffee” task present.endThis new controller which was generated for us contains theseven RESTful controller methods, which are explained inthe following table (inspired by David Heinemeier Hansson’sDiscovering a World of Resources on Rails /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 atsheet.pdf):#MethodSampleURL xmlDELETEPOSTDELETEDELETENow, 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 theXML namespace that the Application component is from. Bydefault, an Application uses an absolute layout, where youspecify the x,y of each top level container and component.What we want to build is the following application:Figure 3: The Simple Todo Flex ApplicationTable 1: The seven standard RESTful controller methodsDZone, Inc. www.dzone.com

5Flexible Rails: Flex 3 on Rails 2tech facts at your fingertipsBuilding a Flex Rails Application, continued mx:Panel title "Simple Todo" width "100%"height "100%" We want the ability to create new tasks, delete tasks and renamethem inline in the list. Furthermore, we want to do this in the leastamount of code possible. Normally, I’d build this iteratively; butwe’ll build it all at once. Modify the Todo.mxml file to look like this: mx:HBox width "100%" paddingLeft "5"paddingRight "5"paddingTop "5" ?xml version "1.0" encoding "utf-8"? mx:Label text "New Task"/ mx:Application mx:TextInput id "newTaskTI" width "100%"xmlns:mx "http://www.adobe.com/2006/mxml"width "100%" height "100%" layout "vertical"backgroundGradientColors "[#000000, #CCCCCC]" /mx:HBox creationComplete "svcTasksList.send()" mx:List id "taskList" width "100%" height "100%" mx:Button label "Create" click "createTask()"/ mx:Script editable "true" labelField "name" ![CDATA[dataProvider "{tasksXLC}"import mx.events.ListEvent;import mx.controls.Alert;import mx.rpc.events.ResultEvent;private function createTask():void {svcTasksCreate.send();}private function deleteTask(task:XML):void {svcTasksDestroy.send({ method: "DELETE"});private function updateSelectedTask(event:ListEvent):A Quick Highlight Tour of this Code:var itemEditor:TextInput var selectedTask:XML XML(event.itemRenderer.data);if (selectedTask.name itemEditor.text) return;var params:Object new Object();params['task[name]'] itemEditor.text;params[' method'] "PUT";svcTasksUpdate.url "/tasks/" selectedTask.id ".xml";svcTasksUpdate.send(params);}private function listTasks():void {We use a vertical layout to make the componentsflow vertically. Other choices are horizontal (forhorizontal flow) and absolute (which we saw before). ThebackgroundGradientColors specify the start and end of thegradient fill for the background.1We define a HTTPService svcTasksList, which doesa GET to /tasks.xml (thus triggering the index action ofthe TasksController) and specifies a resultFormat of e4x sothe result of the service can be handled with the new E4XXML API. We then take the lastResult of this service, whichis an XML document, get its children (which is an XMLListof the tasks), and make this be the source of an XMLListCollection called tasksXLC. We do this with a binding tothe source attribute. Similarly, we define svcTasksCreate,svcTasksUpdate and svcTasksDestroy to be used for theother CRUD operations.2svcTasksList.send();}]] /mx:Script mx:HTTPService id "svcTasksCreate" url "/tasks.xml"contentType "application/xml" resultFormat "e4x"method "POST" result "listTasks()" mx:request task name {newTaskTI.text} /name /task /mx:HTTPService mx:HTTPService id "svcTasksList" url "/tasks.xml"We can pass data to Rails via data bindings usingcurly braces { } inside XML (as shown in svcTaskCreate)or by sending form parameters that Rails would be expecting(as shown in the updateSelectedTask method).3 /mx:request resultFormat "e4x" method "POST"/ mx:HTTPService id "svcTasksUpdate" resultFormat "e4x"method "POST" result "listTasks()"/ For svcTasksUpdate and svcTasksDestroy we arenot setting the url property statically, but insteaddynamically setting it to include the id of the task we areupdating or destroying.4 mx:HTTPService id "svcTasksDestroy" resultFormat "e4x"method "POST" result "listTasks()"/ mx:XMLListCollection id "tasksXLC"click "deleteTask(XML(taskList.selectedItem))"/ /mx:ControlBar This is a complete Flex application in 67 lines of code! Compileand run the application by clicking the green “play” button: youwill see the screen shown in Figure 3.void {enabled "{taskList.selectedItem ! null}" /mx:Application } mx:Button label "Delete" width "100%" height "30" /mx:Panel svcTasksDestroy.url "/tasks/" task.id ".xml";itemEditEnd "updateSelectedTask(event)"/ mx:ControlBar width "100%" horizontalAlign "center" enter "createTask()"/ source "{XMLList(svcTasksList.lastResult.children())}"/ DZone, Inc. www.dzone.com

6Flexible Rails: Flex 3 on Rails 2tech facts at your fingertipsRESOURCESA hack: you can’t send HTTP PUT or DELETE from theFlash player in a web browser, so we need to fake it.Luckily, since you can’t send PUT or DELETE from HTML ina web browser either, Rails already has a hack in place—wejust need to know how to use it. Rails will look for a methodparameter in its params hash and, if there is one, use it insteadof the actual HTTP method. So, if we do a form POST witha method of PUT, Rails will pretend we sent an HTTP PUT. (Ifyou’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, {} canbe used for both anonymous object creation and for datacontinuedfromThinkpage 5of an anonymous object like a hash in licationshttp://www.manning.com/armstrongBook: Flexible Rails—providesa code-focused, iterativetutorial introduction to usingFlex with Rails.http://www.manning.com/armstrong2Book: Enterprise FlexibleRails—provides the definitivetutorial introduction to theRuboss Framework.http://www.ruboss.comThe Ruboss Framework: TheOpen Source FrameworkWhich Puts Flex On Rails.Ruboss taking the Flex Railscombination further, makingit even easier and moreaccessible to the Enterprise.RubossTechnologyCorporationABOUT THE AUTHORRECOMMENDED BOOKPeter ArmstrongFlexible Rails is a bookabout how to use Rubyon Rails and Adobe Flexto build next-generationrich Internet applications(RIAs). The book takesyou to the leading edgeof RIA development,presenting examples inFlex 3 and Rails 2.Peter Armstrong is the CEO and Co-Founder of Ruboss Technology Corporation(http://ruboss.com), a self-funded RIA startup in Vancouver, BC, Canada. Peter isalso the co-creator of the open source Ruboss Framework, the RESTful way to developAdobe Flex and AIR applications that easily int egrate with Ruby on Rails. Peter isthe author of Flexible Rails and Enterprise Flexible Rails. Peter has been developingrich client applications for over 7 years. He has worked with Flex full-time since July2004, including being a key part of the Dorado Product Engineering team that won the 2006 AdobeMAX Award for RIA/Web Development ( ).He is the organizer of The Vancouver Ruby/Rails Meetup group and is a frequent conferencespeaker on using Flex and Rails together.BlogBUY rarmstrong.com/Get More FREE Refcardz. Visit refcardz.com now!Upcoming Refcardz:Available:Core SeamEssential RubyEssential MySQLCore CSS: Part IJUnit and EasyMockCore .NETGetting Started with MyEclipseVery First Steps in FlexEquinoxSpring AnnotationsC#EMFCore JavaGroovyCore CSS: Part IINetBeans IDE 6.1 Java EditorPHPRSS and AtomJSP Expression LanguageGetting Started with JPAALM Best PracticesJavaServer FacesGlassFish Application ServerSilverlight 2HTML and XHTMLVisit refcardz.com for a complete listing of available Refcardz.Hibernate SearchXMLStruts2DZone, Inc.1251 NW MaynardCary, NC 27513DZone communities deliver over 4 million pages each month tomore than 1.7 million software developers, architects and decisionmakers. DZone offers something for everyone, including news,tutorials, cheatsheets, blogs, feature articles, source code and more.“DZone is a developer’s dream,” says PC Magazine.FREEDesign PatternsPublished June 2008ISBN-13: 978-1-934238-08-0ISBN-10: 1-934238-08-250795888.678.0399919.678.0300Refcardz Feedback Welcomerefcardz@dzone.comSponsorship Opportunitiessales@dzone.com 7.95Core CSS: Part III9 781934 238080Copyright 2008 DZone, Inc. All rights reserved. No part of this publication may be reproduced, stored in a retrieval system, or transmitted, in any form or by means electronic, mechanical,photocopying, or otherwise, without prior written permission of the publisher. Reference: Flexible Rails: Flex 3 on Rails 2, Peter Armstrong. Manning Publications, 2008.Version 1.0

RESTful Rails controllers, the Rails controller methods will also support the traditional HTML views. 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.

Related Documents:

Note from the Publisher The Ruby on Rails 3 Tutorial and Reference Collectionconsists of two bestselling Rails eBooks: Ruby on Rails 3 Tutorial:Learn Rails by Example by Michael Hartl The Rails 3 Wayby Obie Fernandez Ruby on Rails 3 Tutorial:Learn Rails by Exampleis a hands-on guide to the Rails 3 envi- ronment.Through detailed instruction,you develop your own complete sample

rails dbconsole rails db # starts up the Rails db console Command Shortcut Description Help: All commands can be run with -h for more information rails g scaffold zombie name:string bio:text age:integer rails g migration RemoveEmailFromUser email:string rails g mailer Zombi

Contributing to Ruby on Rails Rails is not 'somebody else's framework.' This guide covers a variety of ways that you can get involved in the ongoing development of Rails. API Documentation Guidelines This guide documents the Ruby on Rails API documentation guidelines. Ruby on Rails Guides Guidelines This guide documents the Ruby on Rails guides .

Plywood IS NOT allowed. G. Guard Rails: All ramps must include guard rails or curb edges to ensure that a wheelchair cannot roll off. (see Handrails for top rail specifications) G (1.) For wood ramps, use either vertical spindles on 4” centers OR toe, mid and top guard rails. Toe guard rails and mid guard rails be must be 2” x 4”.

folders for the Open Rails software to read them into the game engine. Installation of Open Rails software does not modify any MSTS files. Nor does Open Rails software modify any MSTS files during game play. The Open Rails software is not responsible for your inability to access any MSTS train sets, activities, consists, services or routes.

Canopy Assembly and Installation Instructions 1. Assemble Lower Frame Locate (4) Side rails, (2) Front/rear rails and (1) Ridgepole. Connect the two side rails using the splice as shown. Finish Lower frame assembly by attaching the Front/Rear rails to the Side Rails using the Corner Castings.

then turned it into an open-source project that became Ruby on Rails. In Jun 2004, Rails 0.5 was presented to the public as the first time (at IRC). In Dec 2005, Rails 1.0 was the first public release with an incredibly proud. In Dec 2007, Rails 2.0 was a fantastic release with great new features, loads of fixes and an incredible amount of polish.

2 FAMILY DAY 012 CONGREGATIONAL CHURCH OF CHRISTIAN FELLOWSHIP!"# %&' ()* ", O COME LET US ADORE HIM! 12.14.12 HERE AT CHRISTIAN FELLOWSHIP FEATURING THE SANCTUARY CHOIR AND SPECIAL GUESTS. GREETINGS From Rev. James K. McKnight photo by: Julian Murray 2010 WELCOME FAMILY AND FRIENDS! The psalmist wrote ÒI will bless the Lord at all times; His praise shall con - tinually be in my Mouth!Ó .