SlideShare a Scribd company logo
1 of 34
Download to read offline
Ruby On Rails
                               na prática




                            Lukas Alexandre

Saturday, January 19, 13
O que é?
                           Framework;

                           Open Source;

                           Full stack;

                           Focado em Apps com base de dados;

                           MVC - Model / View / Controller;




Saturday, January 19, 13
Overview
                           Ruby é uma linguagem de programação;

                           Rails é um framework que provê
                           infraestrutura web;

                           Rails é escrito em Ruby;




Saturday, January 19, 13
Filosofia do Rails
                           Convention Over Configuration;

                           Don’t Repeat Yourself - DRY;

                           Rails tem opiniões fortes;




Saturday, January 19, 13
Arquitetura do Rails
                           Aplicações Rails usam Model-View-Controller
                           (MVC);

                           Model - ActiveRecord;

                           View - ActionView;

                           Controller - ActionController;




Saturday, January 19, 13
E o Ruby?
                           É uma linguagem interpretada;

                           É extremamente orientada a objetos;

                           TUDO é um objeto;

                           Vem de Perl, Smalltalk e Lisp;




Saturday, January 19, 13
RSS Reader - Criando
                           gem install rails

                           rails new rss_reader

                           cd rss_reader

                           rails server

                           http://localhost:3000

                           Welcome Aboard!!!


Saturday, January 19, 13
Estrutura de diretórios

                       /app

                           /controllers

                           /helpers

                           /models

                           /views/nome_do_controller


Saturday, January 19, 13
Estrutura de diretórios

                       /config         /log

                       /db            /public

                       /doc           /test

                       /lib           /tmp



Saturday, January 19, 13
Modos de execução
                           Desenvolvimento (development)

                           Teste (test)

                           Produção (production)




Saturday, January 19, 13
Welcome Aboard - E agora?

                       No terminal:

                              rails generate scaffold feed name:string

                              rake db:migrate

                              rm public/index.html

                       routes.rb

                              root :to => 'feeds#index'


Saturday, January 19, 13
Res...what?? Restful!
                           Index - Listagem dos recursos

                           Show - Detalhes do recurso

                           New - Preenchendo um novo recurso

                           Create - Criando um novo recurso

                           Edit - Preenchendo os dados de um recurso existente

                           Update - Atualizando um recurso

                           Destroy - Removendo um recurso


Saturday, January 19, 13
Verbalizando a Web
                               (http verbs)
                           Get

                           Post

                           Put

                           Delete




Saturday, January 19, 13
Rotas...hã?
                           http://localhost:3000/feeds/hello_world

                           http://localhost:3000 - endereco e porta do
                           servidor

                           feeds - nome do controlador

                           hello_world - nome da ação (método no
                           controller)




Saturday, January 19, 13
Armazenando os dados
                       config/database.yml

                       development:

                           adapter: sqlite3

                           database: db/development.sqlite3

                           pool: 5

                           timeout: 5000


Saturday, January 19, 13
Models, o que são e para
                        onde vão?
                       class Feed < ActiveRecord::Base

                           attr_accessible :name

                       end



                       Negociar;

                       Representar;


Saturday, January 19, 13
Migrations
                           Ficam em db/migrations;

                           Versionamento do banco;

                           Devem ser criadas a cada alteração da
                           estrutura de dados;

                           Esqueleto do banco (schema.rb);

                           Reversíveis;



Saturday, January 19, 13
Como se parecem:
                       class CreateFeeds < ActiveRecord::Migration
                         def change
                           create_table :feeds do |t|
                             t.string :name

                           t.timestamps
                          end
                        end
                       end


Saturday, January 19, 13
E as Views?!
                       app/views/feeds/index.html.erb

                       <% @feeds.each do |feed| %>

                           <tr>

                            <td><%= feed.name %></td>

                            <td><%= link_to 'Show', feed %></td>

                            <td><%= link_to 'Edit', edit_feed_path(feed) %></td>

                          <td><%= link_to 'Destroy', feed, method: :delete, data: { confirm: 'Are you
                       sure?' } %></td>

                           </tr>

                       <% end %>




Saturday, January 19, 13
Convention over Configuration

                           O model de Feed “automagicamente” procura
                           por uma tabela em seu plural;

                           O controller “automagicamente” acha e
                           renderiza as views corretas usando seu nome
                           e ação executada (views/feeds/index.html);




Saturday, January 19, 13
Feed sem nome??
                             Validações nele!
                       validates_presence_of
                       validates_length_of
                       validates_acceptance_of
                       validates_uniqueness_of
                       validates_format_of
                       validates_numericality_of
                       validates_inclusion_in
                       validates_exclusion_of
                       Entre outros...


Saturday, January 19, 13
E como ficaria?
                       class Feed < ActiveRecord::Base
                         attr_accessible :name

                        validates_presence_of :name
                       end




Saturday, January 19, 13
E os itens do feed?
                       rails generate scaffold feed_item
                       feed:references title:string content:text

                       rake db:migrate




Saturday, January 19, 13
Associations...a rede social
                            dos models
                           has_one

                           belongs_to

                           has_many

                           has_and_belongs_to_many

                           has_many :model1, :through => :model2

                           has_one :model1, :through => :model2


Saturday, January 19, 13
E no nosso caso?

                       class FeedItem < ActiveRecord::Base
                         belongs_to :feed
                         attr_accessible :content, :title
                       end
                       class Feed < ActiveRecord::Base
                         has_many :feed_items
                         ...
                       end


Saturday, January 19, 13
Mostrando itens por feed
                       app/views/feeds/show.html.erb

                       <section>
                         <% @feed.feed_items.each do |feed_item| %>
                          <article>
                            <header>
                              <h1><%= feed_item.title %></h1>
                            </header>
                            <p>
                              <%= feed_item.content %>
                            </p>
                          </article>
                         <% end -%>
                       </section>


Saturday, January 19, 13
Mergulhando no
                                ActiveRecord
                           Querys SQL complexas;

                             Join

                             Left Join

                           Agrupando;

                           Ordenando;




Saturday, January 19, 13
Porque Rails?
                           Resolve 90% dos problemas;

                           Foco no negócio;

                           Ecossistema gigantesco;

                           Comunidade receptiva;

                           Ready to go;




Saturday, January 19, 13
Porque Ruby?
                           Intuitiva;

                           POUCO verbosa;

                           Extremamente dinâmica;

                           Gostosa de escrever;




Saturday, January 19, 13
Ferramentas de trabalho
                           Sublime Text 2 / VIM;

                           Total Terminal;

                           Patterns (Regex);

                           Kindle (armado até os dentes!);




Saturday, January 19, 13
Contato
                           pessoal: lukasalexandre@me.com

                           profissional: lukas@codelogic.me

                           http://github.com/lukasalexandre




Saturday, January 19, 13
Perguntas?




Saturday, January 19, 13
Obrigado!




Saturday, January 19, 13
Referências
                           guides.rubyonrails.org

                           Agile Web Development with Rails




Saturday, January 19, 13

More Related Content

Similar to Introdução Ruby On Rails

Ruby on Rails introduction
Ruby on Rails introduction Ruby on Rails introduction
Ruby on Rails introduction Tran Hung
 
Introduction to Ruby on Rails
Introduction to Ruby on RailsIntroduction to Ruby on Rails
Introduction to Ruby on RailsManoj Kumar
 
Connecting the Worlds of Java and Ruby with JRuby
Connecting the Worlds of Java and Ruby with JRubyConnecting the Worlds of Java and Ruby with JRuby
Connecting the Worlds of Java and Ruby with JRubyNick Sieger
 
From a monolithic Ruby on Rails app to the JVM
From a monolithic  Ruby on Rails app  to the JVMFrom a monolithic  Ruby on Rails app  to the JVM
From a monolithic Ruby on Rails app to the JVMPhil Calçado
 
Picking gem ruby for penetration testers
Picking gem ruby for penetration testersPicking gem ruby for penetration testers
Picking gem ruby for penetration testersPaolo Perego
 
Introduction to Rails - presented by Arman Ortega
Introduction to Rails - presented by Arman OrtegaIntroduction to Rails - presented by Arman Ortega
Introduction to Rails - presented by Arman Ortegaarman o
 
Rails Sojourn: One Man's Journey - Wicked Good Ruby Conference 2013
Rails Sojourn: One Man's Journey - Wicked Good Ruby Conference 2013Rails Sojourn: One Man's Journey - Wicked Good Ruby Conference 2013
Rails Sojourn: One Man's Journey - Wicked Good Ruby Conference 2013Mike Desjardins
 
Your first rails app - 2
 Your first rails app - 2 Your first rails app - 2
Your first rails app - 2Blazing Cloud
 
Camel and JBoss
Camel and JBossCamel and JBoss
Camel and JBossJBug Italy
 
Ruby off Rails (english)
Ruby off Rails (english)Ruby off Rails (english)
Ruby off Rails (english)Stoyan Zhekov
 
Improving Your Heroku App Performance with Asset CDN and Unicorn
Improving Your Heroku App Performance with Asset CDN and UnicornImproving Your Heroku App Performance with Asset CDN and Unicorn
Improving Your Heroku App Performance with Asset CDN and UnicornSimon Bagreev
 
Ruby on Rails Primer
Ruby on Rails PrimerRuby on Rails Primer
Ruby on Rails PrimerJay Whiting
 
Application Architectures in Grails
Application Architectures in GrailsApplication Architectures in Grails
Application Architectures in GrailsPeter Ledbrook
 
40 Drupal modules you should be using in 2013
40 Drupal modules you should be using in 201340 Drupal modules you should be using in 2013
40 Drupal modules you should be using in 2013Mariano
 
JRuby + Rails = Awesome Java Web Framework at Jfokus 2011
JRuby + Rails = Awesome Java Web Framework at Jfokus 2011JRuby + Rails = Awesome Java Web Framework at Jfokus 2011
JRuby + Rails = Awesome Java Web Framework at Jfokus 2011Nick Sieger
 
Applying Evolutionary Architecture on a Popular API
Applying Evolutionary Architecture on a  Popular APIApplying Evolutionary Architecture on a  Popular API
Applying Evolutionary Architecture on a Popular APIPhil Calçado
 
DiUS Computing Lca Rails Final
DiUS  Computing Lca Rails FinalDiUS  Computing Lca Rails Final
DiUS Computing Lca Rails FinalRobert Postill
 

Similar to Introdução Ruby On Rails (20)

Ruby on Rails introduction
Ruby on Rails introduction Ruby on Rails introduction
Ruby on Rails introduction
 
Introduction to Ruby on Rails
Introduction to Ruby on RailsIntroduction to Ruby on Rails
Introduction to Ruby on Rails
 
Connecting the Worlds of Java and Ruby with JRuby
Connecting the Worlds of Java and Ruby with JRubyConnecting the Worlds of Java and Ruby with JRuby
Connecting the Worlds of Java and Ruby with JRuby
 
From a monolithic Ruby on Rails app to the JVM
From a monolithic  Ruby on Rails app  to the JVMFrom a monolithic  Ruby on Rails app  to the JVM
From a monolithic Ruby on Rails app to the JVM
 
Picking gem ruby for penetration testers
Picking gem ruby for penetration testersPicking gem ruby for penetration testers
Picking gem ruby for penetration testers
 
Introduction to Rails - presented by Arman Ortega
Introduction to Rails - presented by Arman OrtegaIntroduction to Rails - presented by Arman Ortega
Introduction to Rails - presented by Arman Ortega
 
Rails Sojourn: One Man's Journey - Wicked Good Ruby Conference 2013
Rails Sojourn: One Man's Journey - Wicked Good Ruby Conference 2013Rails Sojourn: One Man's Journey - Wicked Good Ruby Conference 2013
Rails Sojourn: One Man's Journey - Wicked Good Ruby Conference 2013
 
Your first rails app - 2
 Your first rails app - 2 Your first rails app - 2
Your first rails app - 2
 
Camel and JBoss
Camel and JBossCamel and JBoss
Camel and JBoss
 
Ruby off Rails (english)
Ruby off Rails (english)Ruby off Rails (english)
Ruby off Rails (english)
 
Improving Your Heroku App Performance with Asset CDN and Unicorn
Improving Your Heroku App Performance with Asset CDN and UnicornImproving Your Heroku App Performance with Asset CDN and Unicorn
Improving Your Heroku App Performance with Asset CDN and Unicorn
 
Ruby on Rails Primer
Ruby on Rails PrimerRuby on Rails Primer
Ruby on Rails Primer
 
Application Architectures in Grails
Application Architectures in GrailsApplication Architectures in Grails
Application Architectures in Grails
 
40 Drupal modules you should be using in 2013
40 Drupal modules you should be using in 201340 Drupal modules you should be using in 2013
40 Drupal modules you should be using in 2013
 
JRuby + Rails = Awesome Java Web Framework at Jfokus 2011
JRuby + Rails = Awesome Java Web Framework at Jfokus 2011JRuby + Rails = Awesome Java Web Framework at Jfokus 2011
JRuby + Rails = Awesome Java Web Framework at Jfokus 2011
 
Applying Evolutionary Architecture on a Popular API
Applying Evolutionary Architecture on a  Popular APIApplying Evolutionary Architecture on a  Popular API
Applying Evolutionary Architecture on a Popular API
 
StORM preview
StORM previewStORM preview
StORM preview
 
DiUS Computing Lca Rails Final
DiUS  Computing Lca Rails FinalDiUS  Computing Lca Rails Final
DiUS Computing Lca Rails Final
 
First Day With J Ruby
First Day With J RubyFirst Day With J Ruby
First Day With J Ruby
 
Cors michael
Cors michaelCors michael
Cors michael
 

Recently uploaded

Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...HostedbyConfluent
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsMemoori
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Patryk Bandurski
 
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your Budget
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your BudgetHyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your Budget
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your BudgetEnjoy Anytime
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationSafe Software
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
Azure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAzure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAndikSusilo4
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machinePadma Pradeep
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptxMaking_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptxnull - The Open Security Community
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Scott Keck-Warren
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 

Recently uploaded (20)

Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food Manufacturing
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial Buildings
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
 
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your Budget
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your BudgetHyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your Budget
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your Budget
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
Azure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAzure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & Application
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machine
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptxMaking_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping Elbows
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 

Introdução Ruby On Rails

  • 1. Ruby On Rails na prática Lukas Alexandre Saturday, January 19, 13
  • 2. O que é? Framework; Open Source; Full stack; Focado em Apps com base de dados; MVC - Model / View / Controller; Saturday, January 19, 13
  • 3. Overview Ruby é uma linguagem de programação; Rails é um framework que provê infraestrutura web; Rails é escrito em Ruby; Saturday, January 19, 13
  • 4. Filosofia do Rails Convention Over Configuration; Don’t Repeat Yourself - DRY; Rails tem opiniões fortes; Saturday, January 19, 13
  • 5. Arquitetura do Rails Aplicações Rails usam Model-View-Controller (MVC); Model - ActiveRecord; View - ActionView; Controller - ActionController; Saturday, January 19, 13
  • 6. E o Ruby? É uma linguagem interpretada; É extremamente orientada a objetos; TUDO é um objeto; Vem de Perl, Smalltalk e Lisp; Saturday, January 19, 13
  • 7. RSS Reader - Criando gem install rails rails new rss_reader cd rss_reader rails server http://localhost:3000 Welcome Aboard!!! Saturday, January 19, 13
  • 8. Estrutura de diretórios /app /controllers /helpers /models /views/nome_do_controller Saturday, January 19, 13
  • 9. Estrutura de diretórios /config /log /db /public /doc /test /lib /tmp Saturday, January 19, 13
  • 10. Modos de execução Desenvolvimento (development) Teste (test) Produção (production) Saturday, January 19, 13
  • 11. Welcome Aboard - E agora? No terminal: rails generate scaffold feed name:string rake db:migrate rm public/index.html routes.rb root :to => 'feeds#index' Saturday, January 19, 13
  • 12. Res...what?? Restful! Index - Listagem dos recursos Show - Detalhes do recurso New - Preenchendo um novo recurso Create - Criando um novo recurso Edit - Preenchendo os dados de um recurso existente Update - Atualizando um recurso Destroy - Removendo um recurso Saturday, January 19, 13
  • 13. Verbalizando a Web (http verbs) Get Post Put Delete Saturday, January 19, 13
  • 14. Rotas...hã? http://localhost:3000/feeds/hello_world http://localhost:3000 - endereco e porta do servidor feeds - nome do controlador hello_world - nome da ação (método no controller) Saturday, January 19, 13
  • 15. Armazenando os dados config/database.yml development: adapter: sqlite3 database: db/development.sqlite3 pool: 5 timeout: 5000 Saturday, January 19, 13
  • 16. Models, o que são e para onde vão? class Feed < ActiveRecord::Base attr_accessible :name end Negociar; Representar; Saturday, January 19, 13
  • 17. Migrations Ficam em db/migrations; Versionamento do banco; Devem ser criadas a cada alteração da estrutura de dados; Esqueleto do banco (schema.rb); Reversíveis; Saturday, January 19, 13
  • 18. Como se parecem: class CreateFeeds < ActiveRecord::Migration def change create_table :feeds do |t| t.string :name t.timestamps end end end Saturday, January 19, 13
  • 19. E as Views?! app/views/feeds/index.html.erb <% @feeds.each do |feed| %> <tr> <td><%= feed.name %></td> <td><%= link_to 'Show', feed %></td> <td><%= link_to 'Edit', edit_feed_path(feed) %></td> <td><%= link_to 'Destroy', feed, method: :delete, data: { confirm: 'Are you sure?' } %></td> </tr> <% end %> Saturday, January 19, 13
  • 20. Convention over Configuration O model de Feed “automagicamente” procura por uma tabela em seu plural; O controller “automagicamente” acha e renderiza as views corretas usando seu nome e ação executada (views/feeds/index.html); Saturday, January 19, 13
  • 21. Feed sem nome?? Validações nele! validates_presence_of validates_length_of validates_acceptance_of validates_uniqueness_of validates_format_of validates_numericality_of validates_inclusion_in validates_exclusion_of Entre outros... Saturday, January 19, 13
  • 22. E como ficaria? class Feed < ActiveRecord::Base attr_accessible :name validates_presence_of :name end Saturday, January 19, 13
  • 23. E os itens do feed? rails generate scaffold feed_item feed:references title:string content:text rake db:migrate Saturday, January 19, 13
  • 24. Associations...a rede social dos models has_one belongs_to has_many has_and_belongs_to_many has_many :model1, :through => :model2 has_one :model1, :through => :model2 Saturday, January 19, 13
  • 25. E no nosso caso? class FeedItem < ActiveRecord::Base belongs_to :feed attr_accessible :content, :title end class Feed < ActiveRecord::Base has_many :feed_items ... end Saturday, January 19, 13
  • 26. Mostrando itens por feed app/views/feeds/show.html.erb <section> <% @feed.feed_items.each do |feed_item| %> <article> <header> <h1><%= feed_item.title %></h1> </header> <p> <%= feed_item.content %> </p> </article> <% end -%> </section> Saturday, January 19, 13
  • 27. Mergulhando no ActiveRecord Querys SQL complexas; Join Left Join Agrupando; Ordenando; Saturday, January 19, 13
  • 28. Porque Rails? Resolve 90% dos problemas; Foco no negócio; Ecossistema gigantesco; Comunidade receptiva; Ready to go; Saturday, January 19, 13
  • 29. Porque Ruby? Intuitiva; POUCO verbosa; Extremamente dinâmica; Gostosa de escrever; Saturday, January 19, 13
  • 30. Ferramentas de trabalho Sublime Text 2 / VIM; Total Terminal; Patterns (Regex); Kindle (armado até os dentes!); Saturday, January 19, 13
  • 31. Contato pessoal: lukasalexandre@me.com profissional: lukas@codelogic.me http://github.com/lukasalexandre Saturday, January 19, 13
  • 34. Referências guides.rubyonrails.org Agile Web Development with Rails Saturday, January 19, 13