Upgrade to Pro
— share decks privately, control downloads, hide ads and more …
Speaker Deck
Features
Speaker Deck
PRO
Sign in
Sign up for free
Search
Search
Rails 2, arrumando a casa! - Abril 2008
Search
Sylvestre Mergulhão
April 01, 2008
Technology
50
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
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
170
Scaling Rails: Redeparede.com servindo 7,5 milhões por mês - Palestra - Junho 2009
mergulhao
2
170
Empreendedorismo on Rails - Apresentação - Novembro 2008
mergulhao
1
100
Empreendedorismo on Rails - Palestra - Novembro 2008
mergulhao
1
100
Utilizando Bluetooth com Ruby - Palestra - Outubro 2008
mergulhao
1
74
Lucidus: Rails + XP = produtividade - Abril 2008
mergulhao
1
93
Nos Trilhos Com Rails (Versao Atualizada) - Palestra Conisli - Novembro 2007
mergulhao
1
56
GNU, Linux e Software Livre: encaixando as peças do quebracabeça - Palestra - Novembro 2007
mergulhao
1
67
Other Decks in Technology
See All in Technology
Genie Codeハンズオン応用編
taka_aki
0
110
AI-DLC実践録_フルサイクル開発への挑戦
miyuc
0
220
ブラウザ研修 2026
recruitengineers
PRO
6
1.1k
AIコーディングの次。コードレビューと理解負荷を解消して組織の開発生産性を高める
moongift
PRO
2
2.6k
Genie Codeハンズオン基礎編
taka_aki
1
130
制約理論(ToC)入門 2026版
recruitengineers
PRO
8
2.4k
[ChatGPT Work LT]事務作業が苦手な人のための バックオフィスの「半」自動化
chimaki_iot
0
310
ボトムアップ文化が強い組織で セキュリティをどう根付かせていくかの現在進行形の話 / Making Security Stick in a Bottom-Up Organization
yamaguchitk333
0
240
Sets in Go
ramalho
1
950
【AG-UI × A2UI × MCP Apps】Generative UIをやさしく解説する
nrinetcom
PRO
1
140
修正PRを食べてレビュースキルが賢くなる:Claude Codeによる自己改善サイクル
yuyaumetsu
6
1.6k
DatadogのBits Chatが開発組織にもたらしたもの / What Bits Chat Has Brought Us
sms_tech
1
280
Featured
See All Featured
Git: the NoSQL Database
bkeepers
PRO
432
67k
Fashionably flexible responsive web design (full day workshop)
malarkey
408
67k
Marketing to machines
jonoalderson
1
5.7k
Kristin Tynski - Automating Marketing Tasks With AI
techseoconnect
PRO
0
470
技術選定の審美眼(2025年版) / Understanding the Spiral of Technologies 2025 edition
twada
PRO
120
120k
The AI Revolution Will Not Be Monopolized: How open-source beats economies of scale, even for LLMs
inesmontani
PRO
3
3.7k
Art, The Web, and Tiny UX
lynnandtonic
304
22k
Skip the Path - Find Your Career Trail
mkilby
1
180
エンジニアに許された特別な時間の終わり
watany
108
250k
How Fast Is Fast Enough? [PerfNow 2025]
tammyeverts
3
770
SEO in 2025: How to Prepare for the Future of Search
ipullrank
3
3.7k
brightonSEO & MeasureFest 2025 - Christian Goodrich - Winning strategies for Black Friday CRO & PPC
cargoodrich
3
770
Transcript
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