Ruby On Flex

In Flex on Rails we walked through how to generate data in rails to be consumed by a Flex UI. Now to close the loop lets demonstrate how to post information from Flex to Ruby on Rails. For this example we are going to create a user login UI in Flex and have a rails action validate the user name and password. To get started lets show the MXML code for the Flex UI:

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

  <mx:Script>
    <![CDATA[
      import mx.rpc.events.ResultEvent

      private function getback( event:ResultEvent ):void {
        panel.title = "Login "+event.result.login
      }
    ]]>
  </mx:Script>

  <mx:HTTPService
    id="loginSubmit" url="http://localhost:3000/mycontroller/login"
    result="getback(event);"
  >
    <mx:request>
      <username>{username.text}</username>
      <password>{password.text}</password>
      <application_name>myapp-0.1</application_name>
    </mx:request>
  </mx:HTTPService>

  <mx:Panel id="panel" title="Login"
    paddingBottom="10" paddingTop="10"
    paddingLeft="10" paddingRight="10"
  >
    <mx:HBox>
      <mx:Label text="Username"/>
      <mx:TextInput id="username"/>
    </mx:HBox>
    <mx:HBox>
      <mx:Label text="Password"/>
      <mx:TextInput id="password"/>
    </mx:HBox>
    <mx:Button label="Submit" click="loginSubmit.send()"/>
  </mx:Panel>
</mx:Application>

mx:HTTPService element. The HTPPService object will send data defined in the content of the mx:request tag. In this case, the username and password elements will be used as parameter names for the data. Also notice that the text between the curly braces will resolve to ActionScript code which returns the text entered in the identified mx:TextInput field.

Now that the Flex UI code has been detailed lets proceed to what we can do in rails. I won’t get into the details of user authentication here, perhaps in another post, so lets assume that the method to authenticate the user does the right thing. The values submitted from the mx:HTTPService element in Flex are available in the rails params hash. Here the rails action to authenticate a username and password.

def login
  @user = User.authenticate(params[:username], params[:password])
  render :layout => false
end

To communicate the success or failure of the user authentication render an xml document. For this example, create a login.rxml view and add the following:

if @user.nil?
  xml.login "failure"
else
  xml.login "success"
end

Technorati Tags: , , , , ,


Leave a Reply