Ruby on Rails Best Practices
http://rubyonrails.org
Wondering why Ruby is so popular? Its fans call it a beautiful, artful language. And yet, they say it’s handy and practical.
http://www.ruby-lang.org/
Vladimir Tkach
How to?
© SAP 2007 / Page 2
Rails Best Practices
© SAP 2007 / Page 3
Concept: What’s good code?
© SAP 2007 / Page 4
Move finder to named_scope / scope
© SAP 2007 / Page 5
Use model association
© SAP 2007 / Page 6
Use scope access
© SAP 2007 / Page 7
Add model virtual attribute
© SAP 2007 / Page 8
Use model callback
© SAP 2007 / Page 9
Use Model Callback
© SAP 2007 / Page 10
%>
Replace Complex Creation with Factory Method
© SAP 2007 / Page 11
Replace Complex Creation with Factory Method
© SAP 2007 / Page 12
Move Model Logic into the Model
© SAP 2007 / Page 13
model.collection_model_ids (many-to-many)
© SAP 2007 / Page 14
model.collection_model_ids (many-to-many)
© SAP 2007 / Page 15
model.collection_model_ids (many-to-many)
© SAP 2007 / Page 16
Nested Model Forms (one-to-one)
© SAP 2007 / Page 17
Nested Model Forms (one-to-one)
© SAP 2007 / Page 18
Nested Model Forms (one-to-many)
© SAP 2007 / Page 19
Keep Finders on Their Own Model
© SAP 2007 / Page 20
Keep Finders on Their Own Model
© SAP 2007 / Page 21
Love named_scope
© SAP 2007 / Page 22
Love named_scope
© SAP 2007 / Page 23
the Law of Demeter
© SAP 2007 / Page 24
DRY: Metaprogramming
© SAP 2007 / Page 25
DRY: Metaprogramming
© SAP 2007 / Page 26
Extract into Module
© SAP 2007 / Page 27
Extract to composed class
© SAP 2007 / Page 28
Extract to composed class
© SAP 2007 / Page 29
Use Observer
© SAP 2007 / Page 30
Use Observer
© SAP 2007 / Page 31
Move code into controller
© SAP 2007 / Page 32
Move code into model
© SAP 2007 / Page 33
Move code into helper
© SAP 2007 / Page 34
Replace instance variable with local variable
© SAP 2007 / Page 35
© SAP 2007 / Page 36
§ http://www.ruby-lang.org/en/ § http://www.ruby-lang.org/en/documentation/ § http://rubyonrails.org/ § http://guides.rubyonrails.org/v2.3.8/index.html
§ http://teamco-anthill.blogspot.com
Thank you!