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

Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersThousandEyes
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxOnBoard
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure servicePooja Nehwal
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Paola De la Torre
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
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
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
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
 
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...gurkirankumar98700
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
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)

Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptx
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
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
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
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
 
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
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