Upgrade to Pro
— share decks privately, control downloads, hide ads and more …
Speaker Deck
Sign up for free
Menu
Search
Features
All features
Private URLs
Password Protection
Custom URLS
Scheduled publishing
Remove Branding
Restrict embedding
Deck Collections
Notes
Features
All features
Private URLs
Password Protection
Custom URLS
Scheduled publishing
Remove Branding
Restrict embedding
Deck Collections
Notes
Explore
Featured decks
Featured speakers
Programming
Technology
Storyboards
Explore
Featured decks
Featured speakers
Programming
Technology
Storyboards
Pricing
Search
Sign in
Sign up for free
Rails 2, arrumando a casa! - Abril 2008
Search
Sylvestre Mergulhão
April 01, 2008
Technology
56
1
Share
Embed
Copy iframe code
Copy JS code
Copy link
Start on current slide
Rails 2, arrumando a casa! - Abril 2008
Sylvestre Mergulhão
April 01, 2008
Transcript
52 slides
Rails 2 Arrumando a casa! mergulhaoinfo Sylvestre Mergulhão –
[email protected]
– FISL 2008
Agenda • Rails 2 é menos, e daí? • ActiveRecord
• ActionController e ActionView • Outros • Depreciações/Remoções • Uma migração sem traumas
Rails 2 é menos, e daí? • Lançado no início
de dezembro de 2007 • Rails 2 é menos! • Por quê? • Várias extrações do core
ActiveRecord
validates_numericality_of :salary, :greater_than => 39999 validates_numericality_of :ten, :equal_to => 10
validates_numericality_of :bonus, :less_than => 5000 validates_numericality_of :bonus, :less_than_or_equal_to => 4999 validates_numericality_of :prime, :odd => true validates_numericality_of :squared, :even => true ActiveRecord: Validations
Rails 1.x ActiveRecord: Validations validates_numericality_of :rating, :if => Proc.new {
|post| not post.rating.blank? } validates_numericality_of :rating, :allow_blank => true Rails 2
Query caching Antes do Rails 2 não existia cache de
queries
None
Query caching Rails não utiliza threads, então o cache vale
basicamente para um request
Sexy migrations: Condensed Column Declarations
# The old way class CreatePosts < ActiveRecord::Migration # Create
a table holding blog posts create_table :posts do |t| t.column :user_id, :integer, :null => false t.column :category_id, :integer, :null => false t.column :body, :text # Standard auto-magic columns t.column :created_at, :datetime t.column :updated_at, :datetime end def self.down drop_table :posts end end
class CreatePosts < ActiveRecord::Migration # Create a table holding blog
posts create_table :posts do |t| t.references :user, :category, :null => false t.text :body t.timestamps end def self.down drop_table :posts end end
Foxy fixtures
class Company < ActiveRecord::Base has_many :employees end class Employee <
ActiveRecord::Base belongs_to :company end
# companies.yml yfactorial: id: 1 name: yFactorial, LLC created_at: <%=
Time.now %> updated_at: <%= Time.now %> # employees.yml ryan: id: 1 name: Ryan Daigle company_id: 1 created_at: <%= Time.now %> updated_at: <%= Time.now %>
# companies.yml yfactorial: name: yFactorial, LLC # employees.yml ryan: name:
Ryan Daigle company: yfactorial
Foxy fixtures: Many to Many Associations
class Company < ActiveRecord::Base has_and_belongs_to_many :industry_associations, :join_table => 'company_industry_associations' end
class IndustryAssociation < ActiveRecord::Base has_and_belongs_to_many :companies, :join_table => 'company_industry_associations' end
Não é necessário company_industry_associations.yml Foxy fixtures: Many to Many Associations
# companies.yml yfactorial: name: yFactorial, LLC industry_associations: ruby, webservices
ActionController e ActionView
Asset servers Normalmente seu site contém: • Html • Javascript
• Css • Imagens
Os navegadores limitam a 2 a quantidade de conexões para
um mesmo domínio Asset servers
None
config/environments/production.rb config.action_controller.asset_host = "http://asset%d.site.com"
Asset cache stylesheet_link_tag "application", "forms", :cache => true Em desenvolvimento
nada muda... em produção os css são combinados e incluidos na página como stylesheets/all.css
javascript_include_tag :defaults, :cache => true O mesmo vale para javascript
Asset cache
Cookiebased session Até o Rails 1.2.x as sessões podiam ficar:
• No banco • Em arquivo no servidor
No Rails 2 foi implementada a sessão baseada em cookie.
Mais rápido que ir ao banco ou buscar um arquivo no disco. Cookiebased session
Simple Http Authentication Para que? Para autenticação de webservices
class AdminController < ApplicationController before_filter :authenticate def authenticate authenticate_or_request_with_http_basic do
|name, pass| User.admin?(name, pass) end end end
Rotas RESTful map.resources :comments map.resources :posts do |post| post.resources :comments
end post_comments_path(post) >> /posts/:post_id/comments new_post_comment_path(post) >> /posts/:post_id/comments/new
Outros
Limpando seu enviroment.rb Até o Rails 1.2.6 tudo que precisava
ser carregado em todos os ambientes e “pequenos” monkey patchs – aka gambis / pog / etc – acabavam caindo no enviroment.rb
Limpando seu enviroment.rb # config/initializers/mail.rb ActionMailer::Base.delivery_method = :sendmail ActionMailer::Base.default_charset =
"utf-8"
Limpando seu enviroment.rb # config/initializers/date_formats.rb custom_date_formats = { :concise =>
"%d.%b.%y", :medium => "%b %e, %Y" } ActiveSupport::CoreExtensions::Date::Conversions::DATE_ FORMATS.merge!(custom_date_formats)
Collection Fixtures # The old way def test_post_find assert_equal [posts(:rails2),
posts(:peepcode)], Post.find(:all) end # The new way def test_post_find assert_equal posts(:rails2, :peepcode), Post.find(:all) end
Novas tasks rake db:create RAILS_ENV=test rake db:create:all rake db:reset RAILS_ENV=test
VERSION=23 rake db:rollback STEP=2 rake db:version
Novas tasks messages GET /messages {:action=>"index", :controller=>"messages"} formatted_messages GET /messages.:format
{:action=>"index", :controller=>"messages"} POST /messages {:action=>"create", :controller=>"messages"} rake routes
Novas tasks app/controllers/ratings_controller.rb: * 11 (TODO) Fill out error handling
here app/helpers/profiles_helper.rb: * 18 (FIXME) This breaks unit test rake notes rake notes:fixme rake notes:optimize rake notes:todo
Depreciações e Remoções
Extinção de variáveis de instância @params, @session, @flash, @request e
@env Já estavam depreciadas desde Rails 1.2
find_all virou find(:all) # The wrong way Article.find_all Article.find_first #
The right way Article.find(:all) Article.find(:first)
Extinção de start_form_tag/end_form_tag <% form_for :article, @article, :url => articles_path
do |f| %> <%= f.text_field :title %> <%= submit_tag "Save" %> <% end %>
Plugins acts_as do ActiveRecord Todos foram removidos do core e
estão disponíveis como plugins: http://svn.rubyonrails.org/rails/plugins
Plugin de paginação O sistema de paginação original do Rails
foi removido will paginate http://rock.errtheblog.com/will_paginate
Drivers para banco de dados não default saem do core
Mysql, sqlite e postgresql continuam no core sudo gem install activerecordoracleadapter
Uma migração sem traumas
Finalizando
Possíveis futuros projetos open source
Blog: http://mergulhao.info
Obrigado! Sylvestre Mergulhão
[email protected]
mergulhaoinfo
More Decks by Sylvestre Mergulhão
See All by Sylvestre Mergulhão
Heroku - Plataform as a Service
mergulhao
2
190
Como contratar software?
mergulhao
1
180
Scaling Rails: Redeparede.com servindo 7,5 milhões por mês - Palestra - Junho 2009
mergulhao
2
180
Empreendedorismo on Rails - Apresentação - Novembro 2008
mergulhao
1
110
Empreendedorismo on Rails - Palestra - Novembro 2008
mergulhao
1
110
Utilizando Bluetooth com Ruby - Palestra - Outubro 2008
mergulhao
1
77
Lucidus: Rails + XP = produtividade - Abril 2008
mergulhao
1
100
Nos Trilhos Com Rails (Versao Atualizada) - Palestra Conisli - Novembro 2007
mergulhao
1
60
GNU, Linux e Software Livre: encaixando as peças do quebracabeça - Palestra - Novembro 2007
mergulhao
1
71
Other Decks in Technology
See All in Technology
OCI Artifact による自動運転タクシーに向けた OTA 基盤の構築
biwashi
1
150
20261113_JAWS_Osaka
takuyay0ne
1
590
お風呂場をサーバルームにしよう
yusuke427
0
360
Biohub - Cell Tracking During Development 5th place solution
rist
0
180
SORACOM × AWS IoT Core でSREする
butadora
0
120
IP重複は"ランディングVPC"で受け止める ― PrivateLink と Transit Gatewayによるマルチテナント接続基盤の設計
hatahata021
3
250
農家は秘伝のタレを知らない - NOBODY KNOWS THE HIDDEN SOURCE - Kaggriculture 3rd Place Solution
masspeaks
2
540
[NW-JAWS DAY]「うちのAWS、インターネット出られないんで」― AWS外の自社サービスをPrivateLinkでシュッと公開する方法
ykimi
3
890
こんなに変わった! AWSネットワークの常識
shotashiratori
16
11k
マネジメントされる側の仕事は「文句」を言うこと
riyaamemiya
7
5.8k
速くなるほど、深く考える AI時代のQAに学ぶ
kobayashiyorimitsu
0
270
目を覚ませ!僕らの認証情報が何者かに侵略されてるぞ
tkito
2
470
Featured
See All Featured
Marketing Yourself as an Engineer | Alaka | Gurzu
gurzu
0
380
How To Speak Unicorn (iThemes Webinar)
marktimemedia
1
640
Why Our Code Smells
bkeepers
PRO
340
58k
Scaling GitHub
holman
464
140k
The AI Revolution Will Not Be Monopolized: How open-source beats economies of scale, even for LLMs
inesmontani
PRO
3
3.8k
Deep Space Network (abreviated)
tonyrice
0
420
Making Projects Easy
brettharned
120
6.9k
Evolving SEO for Evolving Search Engines
ryanjones
0
360
Helping Users Find Their Own Way: Creating Modern Search Experiences
danielanewman
31
3.4k
4 Signs Your Business is Dying
shpigford
187
23k
Building Experiences: Design Systems, User Experience, and Full Site Editing
marktimemedia
1
670
Embracing the Ebb and Flow
colly
88
5.2k