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
53
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
97
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
SREは、MCPとAutopilotをこう使え!
kazumax55
3
970
事業課題から技術的負債に向き合う
sansantech
PRO
2
2.4k
地方移住と都心キャリアの両立は「金・時間・人」のリソースをフル活用すれば実現できる!〜Snowflake女子会 vol.8
snowwmn0824
0
120
AI coding 整合正規方法
philipz
0
550
AWS DevOps Agent スキルをつかいこなそう / Master AWS DevOps Agent Skills
kinunori
1
480
Why Agent Cost Needs Observability
nttcom
0
160
認知負荷を吸収し、プロダクトをまたぐPR Preview基盤の設計事例
taiki45
2
310
おい、エージェントを使って終わらせろ
nwiizo
3
940
特殊変数大全
dak2
0
130
バイブコーディング時代のWebアプリ開発入門~Cloud Runで学ぶセキュアなビルドとデプロイ
waiwai2111
1
150
HolmesGPTで始めるSREエージェント入門!プラットフォームの障害調査はAIにお任せ 〜
sanghyuk
0
150
作って終わりじゃないサーバーレス 〜9年運用する大規模EC物流API基盤の設計・運用のリアル〜
zozotech
PRO
0
530
Featured
See All Featured
RailsConf & Balkan Ruby 2019: The Past, Present, and Future of Rails at GitHub
eileencodes
141
35k
Agile Leadership in an Agile Organization
kimpetersen
PRO
0
240
Bioeconomy Workshop: Dr. Julius Ecuru, Opportunities for a Bioeconomy in West Africa
akademiya2063
PRO
1
370
Dominate Local Search Results - an insider guide to GBP, reviews, and Local SEO
greggifford
PRO
0
340
Producing Creativity
orderedlist
PRO
348
41k
ピンチをチャンスに:未来をつくるプロダクトロードマップ #pmconf2020
aki_iinuma
128
56k
Save Time (by Creating Custom Rails Generators)
garrettdimon
PRO
33
4.9k
The Psychology of Web Performance [Beyond Tellerrand 2023]
tammyeverts
49
3.6k
Amusing Abliteration
ianozsvald
1
310
Designing Dashboards & Data Visualisations in Web Apps
destraynor
232
55k
Tell your own story through comics
letsgokoyo
1
1.1k
Building Experiences: Design Systems, User Experience, and Full Site Editing
marktimemedia
1
610
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