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
72
Lucidus: Rails + XP = produtividade - Abril 2008
mergulhao
1
92
Nos Trilhos Com Rails (Versao Atualizada) - Palestra Conisli - Novembro 2007
mergulhao
1
54
GNU, Linux e Software Livre: encaixando as peças do quebracabeça - Palestra - Novembro 2007
mergulhao
1
66
Other Decks in Technology
See All in Technology
エンジニアリング戦略の作り方 / Crafting Engineering Strategy
iwashi86
19
6.4k
新規事業を牽引する技術選定 〜フルスタックTypeScript開発の実践事例〜
nullnull
3
380
Disciplined Vibes: Scaling AI-Assisted Engineering
sheharyar
0
130
価格.comをAI駆動で全面刷新する ー 30年分の技術的負債を返し、次の30年の土台をつくる ー / AI Engineering Summit Tokyo 2026
tkyowa
53
59k
Oracle AI Database@Azure:サービス概要のご紹介
oracle4engineer
PRO
6
1.9k
2026TECHFRESH畢業分享會 - Lightning Talk - 資料也要 CI/CD? 用 Airbyte 自動化資料同步
line_developers_tw
PRO
0
720
小さく始める AI 活用推進 ― 日経電子版 Web チームの事例/nikkei-tech-talk47
nikkei_engineer_recruiting
0
200
日本 Fintech 未来予測レポート 2027〜2028年(オリジナル版)
8maki
0
1.4k
新しいVibe Codingと”自走”について
watany
5
290
LLMにもCAP定理があるという話
harukasakihara
0
280
非エンジニアがClaudeと挑んだ「1ヶ月間プロダクト30本ノック」
askokc
0
270
EventBridge Connection
_kensh
5
690
Featured
See All Featured
Keith and Marios Guide to Fast Websites
keithpitt
413
23k
Templates, Plugins, & Blocks: Oh My! Creating the theme that thinks of everything
marktimemedia
31
2.8k
Navigating Weather and Climate Data
rabernat
0
220
The State of eCommerce SEO: How to Win in Today's Products SERPs - #SEOweek
aleyda
2
11k
Facilitating Awesome Meetings
lara
57
7k
Data-driven link building: lessons from a $708K investment (BrightonSEO talk)
szymonslowik
1
1.1k
ReactJS: Keep Simple. Everything can be a component!
pedronauck
666
130k
The SEO identity crisis: Don't let AI make you average
varn
0
490
世界の人気アプリ100個を分析して見えたペイウォール設計の心得
akihiro_kokubo
PRO
71
40k
The Illustrated Children's Guide to Kubernetes
chrisshort
51
52k
Leveraging Curiosity to Care for An Aging Population
cassininazir
1
270
How to Align SEO within the Product Triangle To Get Buy-In & Support - #RIMC
aleyda
2
1.5k
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