Flex + Ruby On Rails

Blog For Flex And Ruby On Rails :)

Flex With Rails(Basic Interaction)

Here is the basic idea about how we can use rails with  Flex.

There is many ways to communicate Flex with Backend, in that very easy way is ‘ httpservice’.

1)Create database , table and add data in it.

2)create rails application and connect it with database.

3)Fetch data in rails controller and generate xml file from this data.

4)Use HttpService method in Flex to fetch above xml data in Flex.

1)Database

Use any databse and create table in that with inserting some dummy data.
here we are creating database and table  in mysql ,
mysql>create database mydatabase;
mysql>use mydatabase;
Above line to open database to use it

mysql>create table sites(id int primary key,url varchar(40),description varchar(100));
here we have  mydatabase (Database Name), sites (Table Name)

Now Inserting some dummy data in it.
mysql>insert into sites values(1,’http://www.google.com’,’Enables users to search the Web, Usenet, and images.’);
mysql>insert into sites values(2,’http://www.yahoo.com’,’Personalized content and search options. Chatrooms, free e-mail, clubs,

and pager.’);
mysql>insert into sites values(3,’http://www.youtube.com’,’YouTube is a way to getyour videos to the people who matter to you.’);

mysql>select * from sites;
Here we can see data in our table.

2)Rails Application

Create rails application with type below  on command prompt
rails flex_rails

here flex_rails is a name of rails application.
then type this,
cd flex_rails

Now we are in flex_rails application.
Now create controller for our rails application.
ruby script/generate controller site
Our controller is generated.

Now write  the  database name in database.yml file which is located in config folder.
open the flex_rails -> config ->database.yml
There add our database name like  below
development:
adapter: mysql
database: mydatabase
timeout: 5000

We are ready to go for rails code now.
Here we are doing 2 things :
i)Fetch data from our table,
ii)Generate XML file with this data to send to frontend(Flex inour example)

3)Create XML File
Go inside of our rails project there are folder name app , then
go inside of it there is anather folder controllers , inside of it you can see site_controller.rb file.
Path for me here is  C:\flex_rails\app\controllers
Open site_controller.rb file in notepad and we are writting code to fetch data and generate XML.
Copy and Paste this code at your end.
class SiteController < ApplicationController
def index
@all_Data = Site.find(:all)       #  HERE WE ARE FETCHING ALLDATA FROM SITES TABLE IN @all_Data OBJECT
render :layout => false, :action=>’getXML.rxml’   # HERE  WE SENDING ACTION TO getXML.rxml PAGE
end
end

Now go to app folder again there is anather folder named as views, Open it and you will see anather folder site.
open site folder and create there 1 file named as getXML.rxml inside of it.
open this file and write this code in that.

xml.instruct! :xml, :version=>”1.0″
xml.rss(:version=>”2.0″){
xml.channel{
xml.user_name(‘abhi’)
xml.user_session_id(1)
xml.user_id(1)
xml.language(‘en-us’)
@all_Data.each do|i|
xml.item{
xml.url(i.url)
xml.description(i.description)
}
end
}
}

In above code  give look at this code
@all_Data.each do|i|
xml.item{
xml.url(i.url)
xml.description(i.description)
}
end
Here in @all_Data object we have all data, so we  looping it to write data in xml.

Now see this below code:
xml.user_name(‘abhi’)
xml.user_session_id(1)
xml.user_id(1)
Above code has no any use in our this example, But here we can fetch and write data like username or session id
or else data which we are using in rails and want to send with xml to front end.

Here we are finished with our Rails things.Data is fetched and XML is generated.We can see it.
Go on command prompt where we have in our rails application.
Here On  my computer path is   C:\flex_rails\
Then start the rails server
C:\flex_rails\ruby script/server
http://localhost:3000/site/index    Type this in Browser and see the XML.

4) FLEX
I’m using FlexBuilder 3 to do Flex code.
Create new Project in Flex
File – > New -> FlexProject -> Name Of Project Here says FlexWithRails and click on button Finish.
New project FlexWithRails  is created with FlexWithRails.mxml file

Open this FlexWithRails.mxml file and write this code.
<?xml version=”1.0″ encoding=”utf-8″?>
<mx:Application xmlns:mx=”http://www.adobe.com/2006/mxml&#8221; layout=”vertical” backgroundGradientColors=”[#000000,

#70828f]“
alpha=”1″ themeColor=”haloGreen” backgroundGradientAlphas=”[0.9, 0.96]”  viewSourceURL=”srcview/index.html”>

<!– ALL HTTP SERVICES STARTS HERE–>
<!–   url is   Controller Name/Def Name
resultFormat can be array,object,xml,etc
result is a event which is called when we got the data from xml
fault is a event which is called when we not able to connect or fetch  xml cause of any reason
–>
<mx:HTTPService id=”httpSerGetSiteData”
url=”site/index”
resultFormat=”e4x”
result=”resultHandlerFunc(event)”
fault=”faultHandlerFunc(event)”
/>

<!– ALL HTTP SERVICES ENDS HERE–>

<!– ALL SCRIPT CODE STARTS HERE –>
<mx:Script>
<![CDATA[
import mx.rpc.events.FaultEvent;
import mx.rpc.events.ResultEvent;
import mx.controls.Alert;

private function callData():void {
httpSerGetSiteData.send(); //WE SENDING REQUEST TO BACKEND
}

private function resultHandlerFunc(event:ResultEvent):void{
//WE COME HERE WHEN WE FETCH THE DATA FROM XML
//Alert.show(String(event.result));
//Alert.show(String(httpSerGetSiteData.lastResult.channel.item.event_id));
dg.dataProvider = httpSerGetSiteData.lastResult.channel.item;
//GIVING DATA TO DATAGRID WITH ITS dataProvider PROPERTY.
//tHEN DATA CAN BE DISPLAY IN DATAGRID
}

private function faultHandlerFunc(event:FaultEvent):void{
Alert.show(String(event.fault)); // ERROR MESSAGE COMES IF WE ARE NOT

CONNECTING
//WITH XML OR UNABLE TO FETCH XML DATA
}
]]>
</mx:Script>
<!– ALL SCRIPT CODE ENDS HERE –>

<!– ALL DESIGN CODE STARTS HERE –>
<mx:DataGrid id=”dg” width=”100%” height=”200″>
<mx:columns>
<mx:DataGridColumn headerText=”URL” dataField=”url” width=”150″  />
<mx:DataGridColumn headerText=”Description” dataField=”description”/>
</mx:columns>

</mx:DataGrid>
<mx:Button label=”GetData” click=”callData();” />
<!– ALL DESIGN CODE ENDS HERE –>
</mx:Application>

NOW ALL CODE ARE DONE.
Go on File option of FlexBuilder , then click on Export, then click on ReleaseBuild,
Where you can see ProjectName FlexWithRails   is here , and
Application FlexWithRails.mxml is here.
Below it Export To Folder: where you can see  bin-release.
Then click on Finish button. It will export your file at bin-release.
Now open this bin-release folder on your computer. For me the default path is
on Desctop -> My Documents -> Flex Builder 3 -> FlexWithRails ->bin-release
Copy 4 files from there
i)FlexWithRails.html
ii)FlexWithRails.swf
iii)AC_OETags.js
iv)playerProductInstall.swf

AND PASTE THIS ALL FILES IN PUBLIC FOLDER OF OUR RAILS   PROJECT(flex_rails -> public).
Open Browser and type this url

http://localhost:3000/i)FlexWithRails.html

Click on button  GetData and you will see the data  comes in datagrid.

Thats All friends, Tell me if you find any bug or any query relate to this example. I’ll happy to answer you.
:)

About these ads

June 26, 2009 - Posted by | Flex With Rails

No comments yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: