Dando um tempo no tema, mas não esquecendo…
Quero postar algo que pode ser de interesse.
Estou estudando FLEX e vou colocar um passo a passo de como montar uma aplicação usando RUBY, RAILS, FLEX e RUBYAMF.
Não pretendo explicar como instalar e configurar o ambiente, assim é preciso configurar seu ambiente com os componentes e o banco MYSQL para executar este exemplo.
O objetivo deste passo a passo é prover apenas um exemplo, sei que existem muitos na NET, mas tive dificuldades de aplicar estes exemplos e este que estou postando é o resultado de minha pesquisa na NET e da ajuda de um grande profissional que não me deixou desistir (Grato a Luiz e Iuri).
Sendo assim segue o passo a passo que consegui fazer funcionar, onde no FLEX consegui inclui, alterar e excluir um registro.
Check list do Ambiente:
Ruby 1.8.6 <2007-09-24 patchlevel 111> [i386-mswin32]
Rails 2.2.2
mxmlc 3.1.0 build 2710
FLEX 3.0
MySQL 5.0.45
Tudo bem até agora? Então é só prosseguir…
No prompt de comando comece:
C:Estudo>rails -d mysql cadastro
C:Estudo>cd cadastro
C:Estudocadastro>
Testando
C:Estudocadastro>ruby scriptserver
http://localhost:3000/
Altere o arquivo C:Estudocadastroconfigdatabase.yml
Coloque “username” e “password” corretos
Ex: Considerando que o nome do usuário é “aluno” e a senha é “minhasenha” fica assim:
development:
adapter: mysql
encoding: utf8
database: cadastro_development
pool: 5
username: aluno
password: minhasenha
host: localhost
test:
adapter: mysql
encoding: utf8
database: cadastro_test
pool: 5
username: aluno
password: minhasenha
host: localhost
production:
adapter: mysql
encoding: utf8
database: cadastro_production
pool: 5
username: aluno
password: minhasenha
host: localhost
Voltando ao prompt de comando :
C:Estudocadastro>rake db:create
C:Estudocadastro>
ruby script/plugin install http://rubyamf.googlecode.com/svn/trunk/rubyamf
C:Estudocadastro>
ruby script/generate scaffold pessoa nome:string sobrenome:string
C:Estudocadastro>rake db:migrate
Testando
http://localhost:3000/pessoas
Cadastre uma pessoa.
Agora será preciso editar o arquivo C:Estudocadastroappcontrollerspessoas_controller.rb
Neste arquivo localize as def e substitua o antes pelo depois tanto no def index, create, update e destroy
//————————————————————
– def index
————– antes —————–
def index
@pessoas = Pessoa.find(:all)
respond_to do |format|
format.html # index.html.erb
format.xml { render :xml => @pessoas }
end
end
————– depois —————–
def index
@pessoas = Pessoa.find(:all)
respond_to do |format|
format.html # index.html.erb
format.xml { render :xml => @pessoas }
format.amf { render :amf => @pessoas } # <<– Acrescentar
end
end
//————————————
– def create
————– antes —————–
def create
@pessoa = Pessoa.new(params[:pessoa])
respond_to do |format|
if @pessoa.save
flash[:notice] = ‘Pessoa was successfully created.’
format.html { redirect_to(@pessoa) }
format.xml { render :xml => @pessoa, :status => :created, :location => @pessoa }
else
format.html { render :action => “new” }
format.xml { render :xml => @pessoa.errors, :status => :unprocessable_entity }
end
end
end
————– depois —————–
def create
if @is_amf
@pessoa = Pessoa.new({:nome => params[0][:nome], :sobrenome => params[0][:sobrenome]})
else
@pessoa = Pessoa.new(params[:pessoa])
end
respond_to do |format|
if @pessoa.save
flash[:notice] = ‘Pessoa was successfully created.’
format.html { redirect_to(@pessoa) }
format.xml { render :xml => @pessoa, :status => :created, :location => @pessoa }
format.amf { render :amf => “Message Saved” }
else
format.html { render :action => “new” }
format.xml { render :xml => @pessoa.errors, :status => :unprocessable_entity }
format.amf { render :amf => @pessoa.errors }
end
end
end
//————————————
– def update
————– antes —————–
def update
@pessoa = Pessoa.find(params[:id])
respond_to do |format|
if @pessoa.update_attributes(params[:pessoa])
flash[:notice] = ‘Pessoa was successfully updated.’
format.html { redirect_to(@pessoa) }
format.xml { head :ok }
else
format.html { render :action => “edit” }
format.xml { render :xml => @pessoa.errors, :status => :unprocessable_entity }
end
end
end
————– depois —————–
def update
if @is_amf
@pessoa = Pessoa.find(params[0][:id])
@pessoa.nome = params[0][:nome]
@pessoa.sobrenome = params[0][:sobrenome]
else
@pessoa = Pessoa.find(params[:id])
end
respond_to do |format|
if @pessoa.update_attributes(params[:pessoa])
flash[:notice] = ‘Pessoa was successfully updated.’
format.html { redirect_to(@pessoa) }
format.xml { head :ok }
format.amf { render :amf => @pessoa }
else
format.html { render :action => “edit” }
format.xml { render :xml => @pessoa.errors, :status => :unprocessable_entity }
format.amf { render :amf => @pessoa.errors }
end
end
end
//————————————
– def destroy
————– antes —————–
def destroy
@pessoa = Pessoa.find(params[:id])
@pessoa.destroy
respond_to do |format|
format.html { redirect_to(pessoas_url) }
format.xml { head :ok }
end
end
————– depois —————–
def destroy
if @is_amf
@pessoa = Pessoa.find(params[0][:id])
else
@pessoa = Pessoa.find(params[:id])
end
@pessoa.destroy
respond_to do |format|
format.html { redirect_to(pessoas_url) }
format.xml { head :ok }
format.amf { render :amf => ‘delete’ }
end
end
end
//————————————————————
//————————————————————
Voltando ao prompt de comando :
C:Estudocadastro>mkdir appflex
C:Estudocadastro>mkdir publicbin
Agora vamos para o FLEX é claro que se já tiver intimidade com o compilador do FLEX é só adaptar os passos abaixo e continuar na linha de comando, entretanto os passos foram escritos usando a IDE do FLEX.
Novo projeto FLEX
1ª ABA
desmarque “use default location”
coloque no campo “folder” o seguinte “C:Estudocadastro”
Click em NEXT
2ª ABA
coloque no campo “OutPut folder” o seguinte “publicbin”
Click em NEXT
3ª ABA
coloque no campo “Main source folder” o seguinte “appflex”
coloque no campo “Output folder URL” o seguinte “http://localhost:3000/bin”
Click em FINISH
Criar um arquivo com o nome “services-config.xml” no mesmo diretório onde esta o arquivo cadastro.mxml
Segue o conteúdo do arquivo:
<?xml version=”1.0″ encoding=”UTF-8″?>
<services-config>
<services>
<service id=”rubyamf-flashremoting-service”
class=”flex.messaging.services.RemotingService”
messageTypes=”flex.messaging.messages.RemotingMessage”>
<destination id=”rubyamf”>
<channels>
<channel ref=”rubyamf”/>
</channels>
<properties>
<source>*</source>
</properties>
</destination>
</service>
</services>
<channels>
<channel-definition
id=”rubyamf”
class=”mx.messaging.channels.AMFChannel”>
<endpoint uri=”http://localhost:3000/rubyamf/gateway”
class=”flex.messaging.endpoints.AMFEndpoint”/>
</channel-definition>
</channels>
</services-config>
Acesse o menu Project > Properties
selecione o item “Flex Compiler”
Adicione no campo “Additional compiler arguments” o seguinte ” -services “services-config.xml”"
Segue o conteúdo do arquivo cadastro.mxml:
<?xml version=”1.0″ encoding=”utf-8″?>
<mx:Application xmlns:mx=”http://www.adobe.com/2006/mxml” layout=”absolute”>
<mx:Script>
<![CDATA[
import mx.controls.Label;
import mx.controls.Text;
import mx.controls.Alert;
import mx.rpc.events.FaultEvent;
import mx.rpc.events.ResultEvent;
import mx.rpc.http.HTTPService;
import mx.collections.ArrayCollection;
[Bindable]
private var minhasPessoas:ArrayCollection;
//HTTP Service–
private function carregarPessoas():void {
srvPessoas.send();
}
private function httpResult(event: ResultEvent):void {
minhasPessoas = event.result.pessoas.pessoa as ArrayCollection;
}
private function httpFault(event: FaultEvent):void {
Alert.show(event.fault.message, ‘Erro do serviço http’);
}
//————–
//Remote Object–
private function onFault(event:FaultEvent):void {
Alert.show(event.fault.faultString, “Erro”);
}
private function onResult(event:ResultEvent):void {
Alert.show(event.message.body.toString(), ‘Resposta’);
}
private function novaPessoa():void {
pessoaService.create.send({nome: taPessoaNome.text});
carregarPessoas();
}
private function alterarPessoa():void {
pessoaService.update.send({id: taPessoaCodigo.text, nome:taPessoaNome.text});
carregarPessoas();
}
private function apagarpessoa():void {
pessoaService.destroy.send({id: taPessoaCodigo.text});
carregarPessoas();
}
//—————
]]>
</mx:Script>
<mx:Binding source=”lstPessoas.selectedItem.nome” destination=”taPessoaNome.text” />
<mx:Binding source=”lstPessoas.selectedItem.id” destination=”taPessoaCodigo.text” />
<mx:RemoteObject
id=”pessoaService”
fault=”onFault(event)”
source=”PessoasController”
destination=”rubyamf”>
<mx:method name=”update” result=”onResult(event)” />
<mx:method name=”create” result=”onResult(event)” />
<mx:method name=”destroy” result=”onResult(event)” />
</mx:RemoteObject>
<mx:HTTPService
id=”srvPessoas”
url=”http://localhost:3000/pessoas.xml”
result=”httpResult(event)”
fault=”httpFault(event)” />
<mx:List id=”lstPessoas” x=”10″ y=”40″
labelField=”nome”
dataProvider=”{minhasPessoas}”
width=”187″ height=”162″>
</mx:List>
<mx:Button x=”10″ y=”10″ label=”Carregar” id=”btCarregar” click=”carregarPessoas()”/>
<mx:TextArea id=”taPessoaCodigo” x=”63″ y=”234″ height=”23″ width=”45″/>
<mx:Label x=”20″ y=”235″ text=”Código”/>
<mx:Label x=”20″ y=”266″ text=”Nome”/>
<mx:TextArea x=”63″ y=”265″ id=”taPessoaNome” width=”119″ height=”23″/>
<mx:Canvas x=”10″ y=”224″ width=”187″ height=”110″>
<mx:Button x=”10″ y=”78″ label=”+” id=”btNovo” click=”novaPessoa()”/>
<mx:Button x=”61″ y=”78″ label=”-” id=”btExcluir” click=”apagarpessoa()”/>
<mx:Button x=”112″ y=”78″ label=”Alterar” id=”btAlterar” click=”alterarPessoa()”/>
</mx:Canvas>
</mx:Application>
Teoricamente funciona.
Falta muita coisa para aprender e melhorar, mas espero que tenha sido útil.