"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
When To Use Ruby On Rails
1. When to use Ruby on Rails?
Sytse Sijbrandij
sytse@dosire.com
2. Contents
• Ruby
– What is it?
– Advantages
– Disadvantages
• Rails
– What is it?
– Advantages
– Disadvantages
• When to use it
• Reusable best practices
Ruby Beach, Washington, U.S.
Kevin Mc Neal
3. What is Ruby?
• A scripting language more powerful than
Perl and more object-oriented than Python.
• Invented in 1993 with inspiration from Perl,
Phyton, Smalltalk, Eiffel, Ada, and Lisp.
• Designed for programmer productivity and
joy instead of machine efficiency.
• Follows the principle of least surprise, the
language should minimize confusion.
Yukihiro 'Matz' Matsumoto
• It's easy to work with and to love Ruby. Ruby's Architect
4. Ruby Advantages
Elegant
•
Powerful
•
Readable
•
Concise
•
Ruby and Diamond ring
R. M. Rayner
5. describe Bowling do
before(:each) do
Ruby is @bowling = Bowling.new
end
Elegant it quot;should score 0 for gutter gamequot; do
20.times { @bowling.hit(0) }
@bowling.score.should == 0
end
end
class NewBowlingGame extends PHPSpec_Context
{
private $_bowling = null;
public function before()
{
$this->_bowling = new Bowling;
}
public function itShouldScore0ForGutterGame()
{
for ($i=1; $i<=20; $i++) {
$this->_bowling->hit(0);
} $this->spec($this->_bowling->score)->should->equal(0);
}
}
6. Ruby is Powerful
• Object-oriented (everything is an object)
• Dynamic (duck typing)
# Open Ruby's Time class and add a method
class Time
def yesterday
self - 86400
end
end
today = Time.now # => Thu Aug 14 16:51:50 +1200 2008
yesterday = today.yesterday # => Wed Aug 13 16:51:50 +1200 2008
7. Ruby is Readable
• The code comments itself
• Leads to better naming practices
# An example example function for a photo camera program
def shutter_clicked
capture_image if @camera.on? and @camera.memory_available?
end
8. Ruby is Concise
• Very expressive language
• Less lines of code, higher productivity
-199.abs # 199
quot;ruby is coolquot;.length # 12
quot;Your Momquot;.index(quot;uquot;) #2
quot;Nice Day!quot;.downcase.split(//).sort.uniq.join # quot; !acdeinyquot;
say = quot;I love Rubyquot;
say['love'] = quot;*love*quot;
5.times { puts say }
=> quot;I *love* Rubyquot; quot;I *love* Rubyquot; quot;I *love* Rubyquot; quot;I
*love* Rubyquot; quot;I *love* Rubyquot;
10. Ruby is Slow
• About 10x slower than Java, 2x slower than PHP
All benchmarks, x64 Ubuntu, Intel Q6600 Quad
Computer Language Benchmarks Game
11. Ruby is New
• Not many developers or customers
• No common IDE
– Most coders use the Mac text-editor Textmate
– IDEs: RadRails, RubyMine, 3rd Rail, Netbeans
• No common application server
– Passenger's Apache module has momentum
12. Evolution to web frameworks
From 1990 to 2009
Time
Static Dynamic Integrated
Type of site
Marketing Front office Back office
Business role
• Brochure • Communication • Quotations
• Advertising • Ordering • Fulfillment
• Mailings • Legacy systems
Tools HTML editors: PHP + MySQL: Frameworks:
Frontpage Joomla CakePHP (PHP)
Dreamweaver Drupal Grails (Groovy)
Wordpress Django (Phyton)
Typo3 Ruby on Rails (Ruby)
Merb (Ruby)
.Net Sanatra (Ruby)
Sharepoint
13. What is ?
Creator of Ruby on Rails
• Web application framework David Heinemeier Hansson
• Open Source (MIT license)
• Based on a existing
application (Basecamp)
• Provides common needs:
Routing, sessions
–
Database storage
–
Business logic
–
Generate HTML/XML/CSS/Ajax
–
Testing
–
16. Convention over Configuration
• Table and foreign key naming
– Tables are multiples
(users, orders, etc.)
– Foreign key naming: user_id
• Default locations
– MVC, Tests, Languages, Plugins
• Naming
– Class names: CamelCase
– Files: lowercase_underscored.rb
17. Don’t repeat yourself
• Everything is defined in a single,
unambiguous place
• Easier to find code
– Only need to look once
– Can stop looking when found
– Well defined places for most items
• Much easier to maintain code
– Faster to change
– Less inconsistency bugs
18. Model View Controller
• Model
– Object relationships
(users, orders)
• Controller
– Business logic
(perform a payment)
• View
– Visual representation
(generate HTML/XML)
19. Model
• Contains validation and object methods
• Use 'fat' models and 'skinny' controllers to
increase reuse of methods across controllers
class Order < ActiveRecord::Base
has_many :line_items
has_one :user
has_one :email, :through => :user
validates_presence_of :user
validates_numericality_of :amount
def purchase
self.purchase_time = Now
end
end
20. View
• DSL languages #content
.left.column
Erb for ruby & html
• %h2 Welcome to our site!
%p= print_information
Haml improves on erb
• .right.column= render quot;sidebarquot;
Textile for html
•
Sass for css
•
<div id='content'>
<div class='left column'>
<h2>Welcome to our site!</h2>
<p>
<%= print_information %>
</p>
</div>
<div class=quot;right columnquot;>
<%= render quot;sidebarquot; %>
</div>
</div>
21. Controller
Method Resource Verb
• RESTful index /people GET
show /people/12 GET
– Better than SOAP create /people POST
– Easy to understand update /people/12 PUT
delete /people/12 DELETE
– Easy to debug
GET /people/12.xml
– Easy to cache
def show
– Easy to prioritize @person =
Person.find(params[:id])
– No bottleneck respond_to do |wants|
– HTML/XML/JSON wants.html
wants.xml { render :xml
=> @person.to_xml }
end
end
22. Object Relational Mapping
find
Programming object Database row
ORM Tools:
#<User id: 1, login: quot;Sytsequot;, -ActiveRecord
email: quot;sytse@comcoaster.comquot;,
-DataMapper
description: quot;<p>Sytse studied
-iBATIS
Management Science at the
Universi...quot;, avatar_id: 1,
crypted_password:
quot;b6675cab85b541a91e6d0
save
# Examples of finding records
User.find(:all)
User.find(23).articles
User.find_by_first_name('Johnny')
User.order.find(:last).lines_items.count
23. Re-use of code
• Gems and plugins, more then 1300
– For authentication, pagination, testing, etc.
• Git allows easy forking and merging
• Github website allows you to give back
• Acts as a portfolio
24. Agile practices
• Iterations (branch often, merge often)
• Test all the time (TDD, BDD)
Stories > Tests > Code > Continuous Integration
Story example
Feature: Log-in
In order to view my profile
As a Registered member
I want to be required to log-in
Test example
Given /I am the registered member quot;quirequot;/ do
@user = User.new({ :login => 'quire})
@user.save!
end
25. Security
• Rails prevents SQL injection attacks
– Attacher post in form: quot;some_title; DROP TABLE articles;quot;
– In bad code this can be injected:
quot;SELECT * FROM ARTICLES WHERE TITLE = $TITLEquot;
– Rails will be escape the input automatically:
@articles = Article.find(:all,
:conditions => [:title => params[:title]])
• Rails prevents Cross Site Scripting (XSS)
– With html_escape in view: <%=h comment.body %>
27. Rails is inefficient
• Rails uses a lot of memory,
up to 150MB per instance
• Requires more application servers
• Where are your development constrains?
Resource Example application Rails
Man hours 2.200 hours / e22.000 1.000 hours / e10.000
Project duration 15 weeks of changes / e3.000 10 weeks / e2.000
Computing power 2 servers / e2.000 5 servers / e5.000
Total e27.000 e17.000
28. Rails is hard to deploy
• Harder than PHP, better with Passenger
• Lots of moving parts
– Rails, apps, gems, plugins
– Application server, webserver
• Deployment via scripts
– Via the Capistrano tool
– Easy to break something
• Deployment to multiple servers
29. When to use Ruby on Rails?
New code base and DB Existing code and DB
• •
High development speed Low development speed
• •
Complex applications Simple applications
• •
Web deployment Client deployment
• •
Iterative projects Waterfall projects
• •
Development is expensive Deployment is expensive
• •
Fixed price project Hourly rate project
• •
Early adopter client/team Late majority client/team
• •