when to use ruby on rails

Post on 05-Dec-2014

50.382 Views

Category:

Technology

0 Downloads

Preview:

Click to see full reader

DESCRIPTION

To advantages and disadvantages of the Ruby programming language and the Rails framework. Includes advise when to use it and comparisons to PHP.

TRANSCRIPT

When to use Ruby on Rails?

Sytse Sijbrandij

sytse@dosire.com

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

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.

• It's easy to work with and to love Ruby.Yukihiro 'Matz' Matsumoto

Ruby's Architect

Ruby Advantages

• Elegant

• Powerful

• Readable

• Concise

Ruby and Diamond ringR. M. Rayner

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);}

}

describe Bowling dobefore(:each) do@bowling = Bowling.new

end

it "should score 0 for gutter game" do20.times { @bowling.hit(0) }@bowling.score.should == 0

endend

Ruby is Elegant

Ruby is Powerful

• Object-oriented (everything is an object)

• Dynamic (duck typing)

# Open Ruby's Time class and add a methodclass Timedef yesterdayself - 86400

endend

today = Time.now # => Thu Aug 14 16:51:50 +1200 2008yesterday = today.yesterday # => Wed Aug 13 16:51:50 +1200 2008

Ruby is Readable

• The code comments itself

• Leads to better naming practices

# An example example function for a photo camera programdef shutter_clickedcapture_image if @camera.on? and @camera.memory_available?

end

Ruby is Concise

• Very expressive language

• Less lines of code, higher productivity

-199.abs # 199"ruby is cool".length # 12"Your Mom".index("u") # 2"Nice Day!".downcase.split(//).sort.uniq.join # " !acdeiny"

say = "I love Ruby"say['love'] = "*love*"5.times { puts say }=> "I *love* Ruby" "I *love* Ruby" "I *love* Ruby" "I *love* Ruby" "I *love* Ruby"

Ruby Disadvantages

• Ruby is Slow

• Ruby is New

Ruby Fails Falls, Lookout Mountain, U.S.Oscar & L

Ruby is Slow

• About 10x slower than Java, 2x slower than PHP

All benchmarks, x64 Ubuntu, Intel Q6600 QuadComputer Language Benchmarks Game

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

Evolution to web frameworks

Static Dynamic Integrated

From 1990 to 2009Time

Type of site

Tools

Business roleMarketing

• Brochure

• Advertising

Front office

• Communication

• Ordering

• Mailings

Back office

• Quotations

• Fulfillment

• Legacy systems

HTML editors:

Frontpage

Dreamweaver

PHP + MySQL:

Joomla

Drupal

Wordpress

Typo3

.Net

Sharepoint

Frameworks:

CakePHP (PHP)

Grails (Groovy)

Django (Phyton)

Ruby on Rails (Ruby)

Merb (Ruby)

Sanatra (Ruby)

What is ?

• Web application framework• 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

Creator of Ruby on RailsDavid Heinemeier Hansson

Who uses Rails

• Internally:

• Externally:

• style.mtv.com

• www.getsatisfaction.com

• www.basecamp.com

• www.yellowpages.com

• www.twitter.com

• www.yelloyello.nl

Rails Advantages

• Convention over configuration

• Don’t Repeat Yourself

• Object Relational Mapping

• Model View Controller

• Reuse of code

• Agile practices

• Security

Tay Rail Bridge, ScotlandRoss2085

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

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

Model View Controller

• Model– Object relationships

(users, orders)

• Controller– Business logic

(perform a payment)

• View– Visual representation

(generate HTML/XML)

Model

• Contains validation and object methods

• Use 'fat' models and 'skinny' controllers to increase reuse of methods across controllers

class Order < ActiveRecord::Basehas_many :line_itemshas_one :userhas_one :email, :through => :user

validates_presence_of :uservalidates_numericality_of :amount

def purchaseself.purchase_time = Now

endend

View

• DSL languages

• Erb for ruby & html

• Haml improves on erb

• 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="right column"><%= render "sidebar" %>

</div></div>

#content.left.column%h2 Welcome to our site!%p= print_information

.right.column= render "sidebar"

Controller

• RESTful

– Better than SOAP

– Easy to understand

– Easy to debug

– Easy to cache

– Easy to prioritize

– No bottleneck

– HTML/XML/JSON

Method Resource Verb index /people GET show /people/12 GET create /people POST update /people/12 PUT delete /people/12 DELETE

GET /people/12.xml

def show@person =

Person.find(params[:id])respond_to do |wants|

wants.htmlwants.xml { render :xml

=> @person.to_xml }end

end

Object Relational Mapping

# Examples of finding recordsUser.find(:all)User.find(23).articlesUser.find_by_first_name('Johnny')User.order.find(:last).lines_items.count

Programming object Database row

#<User id: 1, login: "Sytse", email: "sytse@comcoaster.com", description: "<p>Sytse studied Management Science at the Universi...", avatar_id: 1, crypted_password: "b6675cab85b541a91e6d0

ORM Tools:-ActiveRecord-DataMapper-iBATIS

find

save

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

Agile practices

• Iterations (branch often, merge often)

• Test all the time (TDD, BDD)

Stories > Tests > Code > Continuous Integration

Story exampleFeature: Log-inIn order to view my profileAs a Registered memberI want to be required to log-in

Test exampleGiven /I am the registered member "quire"/ do@user = User.new({ :login => 'quire})@user.save!

end

Security

• Rails prevents SQL injection attacks– Attacher post in form: "some_title; DROP TABLE articles;"

– In bad code this can be injected:

"SELECT * FROM ARTICLES WHERE TITLE = $TITLE"

– 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 %>

Rails Disadvantages

• Rails is inefficient

• Rails is hard to deploy

Montparnesse 1895Jeff Mc Neill

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

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

When to use Ruby on Rails?

• New code base and DB

• High development speed

• Complex applications

• Web deployment

• Iterative projects

• Development is expensive

• Fixed price project

• Early adopter client/team

• Existing code and DB

• Low development speed

• Simple applications

• Client deployment

• Waterfall projects

• Deployment is expensive

• Hourly rate project

• Late majority client/team

Re-usable best practices

• Don't Repeat Yourself• 'Fat' model, 'skinny' controller• MVC framework

– CakePHP

• Integration testing– Selenium

• DSL's– Textile for markup

• Source code repository– GIT

• Project management– Github, Lighthouse, Basecamp

Recycle shirt by Brian Damage

Questions?

http://www.dosire.com/

top related