SlideShare a Scribd company logo
1 of 49
Download to read offline
RUBY   on


  OSDC.TW 2006
contagious
How Hot is RoR
450,000
                 over 400,000
                  downloads
337,500


225,000


112,500


     0
    2004 July   2004 Dec.   2005 Oct.   2006 April
•   400 seats, sold out in one week

•   extra 150 seats, sold out in 24 hours
David
Heinemeier
 Hansson
Data from BookScan:
Ruby Books sales is up 1,552%
over last year.
RoR is so HOT
Everybody wants to
      clone it
What exactly is
Ruby On Rails
Ruby on Rails is an
open-source web
   framework
optimized for
programmer
 happiness
What Makes Programmer
        Happy?

• Simplicity       • Well organized
 • Easy to learn    • Easy to Maintain
 • Easy to Write
SIMPLE
    Easy to Learn and Write



    No separation between
Business Logic and Display Logic
Corporate Approval
  Well Structured


  Steep Learn Curve
Complex Configuration
 No fast turnaround
Finding the middle
   ground with
Full Stack of MVC
Real World Usage
One Language - Ruby
• Model - View - Controller
• Database Schema generation
• Javascript generation
• XML generation
• Makefile
Convention
   Over
Configuration
CREATE TABLE orders (
  id INTEGER PRIMARY KEY AUTO_INCREMENT,


                                              An
  order_date TIMESTAMP NOT NULL,
  price_total DOUBLE NOT NULL
);


                                           example
CREATE TABLE products (
  id INTEGER PRIMARY KEY AUTO_INCREMENT,


                                            from a
  name VARCHAR(80) NOT NULL,
  price DOUBLE NOT NULL
);


                                           Hibernate
CREATE TABLE order_items (
  id INTEGER PRIMARY KEY AUTO_INCREMENT,


                                            tutorial
  order_id INTEGER NOT NULL,
  product_id INTEGER NOT NULL,
  amount INTEGER NOT NULL,
  price DOUBLE NOT NULL
);
public class Order


                                                  Java
{
    private Integer id;
    private Date date;
    private double priceTotal;

                                                 Object
    private Set orderItems = new HashSet();

    public Order() {


                                                 Model:
        this.date = new Date();
    }
    public Integer getId() {


                                                 Order
        return id;
    }
    public void setId(Integer id) {
        this.id = id;
    }
    public Date getDate() {
        return date;
    }
    public void setDate(date) {
        this.date = date;
    }
    public void addProduct(Product p, int amount) {
    OrderItem orderItem = new OrderItem(this, p, amount);
    this.priceTotal = this.priceTotal + p.getPrice() * amount;
    this.orderItems.add(orderItem);
    }
}
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping
    PUBLIC "-//Hibernate/Hibernate Mapping DTD//EN"
    "http://hibernate.sourceforge.net/hibernate-mapping-2.0.dtd">


                                                             Java
<hibernate-mapping>
    <class name="test.hibernate.Order" table="orders">
        <id name="id" type="string" unsaved-value="null" >
            <column name="id" sql-type="integer" not-null="true"/>

                                                           Database
            <generator class="native"/>
        </id>
        <property name="date">


                                                           Mapping:
         <column name="order_date"
                 sql-type="datetime" not-null="true"/>
        </property>


                                                            Order
        <property name="priceTotal">
        <column name="price_total"
                sql-type="double" not-null="true"/>
        </property>

        <set name="orderItems" table="order_items"
       inverse="true" cascade="all">
            <key column="order_id" />
            <one-to-many class="test.hibernate.OrderItem" />
        </set>
     </class>
</hibernate-mapping>
Rails Data Model:
               Order
class Order < ActiveRecord::Base
  has_many :order_items

  def add_product(product, amount)
    order_item = OrderItem.new(product, amount)
    self.price_total += product.price * amount
    order_items << order_item
  end
end
"opinionated software"
  — sacrificing some
 flexibility in favour of
       simplicity
“much greater
productivity and a better
 developer experience”
Dispatch based on URLs
 http://myapp/orders/show/1

     Application
                   controller
                                action
                                         id
  *customizable by Routing
Action grouped in Controller
class OrdersController < ApplicationController
  def index
    list
    # Default to app/views/orders/index.rhtml
    render :action => 'list'
  end

  def list
    @order_pages, @orders =
           paginate :orders, :per_page => 10
  end

  def show
    @order = Order.find(params[:id])
  end
end
Rendering and Redirection
def update
  @order = Order.find(params[:id])
  if @order.update_attributes(params[:order])
    flash[:notice] =
                 'Order was successfully updated.'
    redirect_to :action => 'show', :id => @order
  else
    render :action => 'edit'
  end
end
Query Data
the_order = Order.find(2)
book = Product.find_by_name(”Programming Ruby”)

small_order = Order.find :first,
     :condition => [”price_total <= ?”, 50.0]
web_books = Product.find :all,
     :condition => [”name like ?”,”%Web%”]

print book.name
print the_order.price_total
Associations
class Order < ActiveRecord::Base
  has_many :order_items
end

the_order = Order.find :first
the_oder.oder_items.each do |item|
    print item.name
end


  * Some other associations: has_one,
belongs_to, has_and_belongs_to_many...
Validations
class Product < ActiveRecord::Base
  validates_presenc_of   :name
  validtaes_numericality :price
end


              Hooks
class Order < ActiveRecord::Base
  def before_destory
      order_items.destory_all
  end
end
Views - Erb
<!-- app/views/product/list.rhtml -->
<% for product in @products -%>
  <p>
    <ul>
       <li> name: <%= product.name %> </li>
       <li> price: <%= product.price %> </li>
    </ul>
    <%= link_to 'Show', :action => 'show',
                         :id => product %>
  </p>
<% end -%>
Sounds Great !!

But it is written in ....

      ?? Ruby ??
Rails makes it fast to
develop, but the true
power behind Rails is


        RUBY
Blocks
• Iteration
   5.times { |i| puts i }
   [1,2,3].each { |i| puts i }

• Resource Management
   File.open(’t.txt’) do |f|
     #do something
   end


• Callback
   TkButton.new do
     text “EXIT”
     command { exit}
   end
New Language Construct
 Rakefile
  task :test => [:compile, :dataLoad] do
    # run the tests
  end


 Markaby
  html do
    body do
      h1 ‘Hello World’
    end
  end
Dynamic Nature

•Open Class
• Runtime Definition
• Code Evaluation
• Hooks
Meta - Programming
class Order < ActiveRecord::Base
  has_many :order_items
end


class Product < ActiveRecord::Base
  validates_presenc_of   :name
  validtaes_numericality :price
end
Syntax Matters

• Succinct
• Easy to Read
• Principle of Least Surprise
Ruby is designed to
make programmers
      Happy
Where Rails Sucks
•Internationalization
• Speed
• Template System
• Stability
• Legacy System
Lack
Resources
    In
 Taiwan
Join Ruby.tw
http://willh.org/cfc/wiki/
Q&A

More Related Content

What's hot

Dirty Secrets of the PHP SOAP Extension
Dirty Secrets of the PHP SOAP ExtensionDirty Secrets of the PHP SOAP Extension
Dirty Secrets of the PHP SOAP Extension
Adam Trachtenberg
 
Hidden Treasures in Project Wonder
Hidden Treasures in Project WonderHidden Treasures in Project Wonder
Hidden Treasures in Project Wonder
WO Community
 
Testing your javascript code with jasmine
Testing your javascript code with jasmineTesting your javascript code with jasmine
Testing your javascript code with jasmine
Rubyc Slides
 
Filtering data with D2W
Filtering data with D2W Filtering data with D2W
Filtering data with D2W
WO Community
 
Venturing Into The Wild: A .NET Developer's Experience As A Ruby Developer
Venturing Into The Wild: A .NET Developer's Experience As A Ruby DeveloperVenturing Into The Wild: A .NET Developer's Experience As A Ruby Developer
Venturing Into The Wild: A .NET Developer's Experience As A Ruby Developer
Jon Kruger
 

What's hot (20)

JQuery introduction
JQuery introductionJQuery introduction
JQuery introduction
 
Rails on Oracle 2011
Rails on Oracle 2011Rails on Oracle 2011
Rails on Oracle 2011
 
How to write easy-to-test JavaScript
How to write easy-to-test JavaScriptHow to write easy-to-test JavaScript
How to write easy-to-test JavaScript
 
Rails-like JavaScript Using CoffeeScript, Backbone.js and Jasmine
Rails-like JavaScript Using CoffeeScript, Backbone.js and JasmineRails-like JavaScript Using CoffeeScript, Backbone.js and Jasmine
Rails-like JavaScript Using CoffeeScript, Backbone.js and Jasmine
 
jQuery & 10,000 Global Functions: Working with Legacy JavaScript
jQuery & 10,000 Global Functions: Working with Legacy JavaScriptjQuery & 10,000 Global Functions: Working with Legacy JavaScript
jQuery & 10,000 Global Functions: Working with Legacy JavaScript
 
jQuery
jQueryjQuery
jQuery
 
Dirty Secrets of the PHP SOAP Extension
Dirty Secrets of the PHP SOAP ExtensionDirty Secrets of the PHP SOAP Extension
Dirty Secrets of the PHP SOAP Extension
 
Jquery introduction
Jquery introductionJquery introduction
Jquery introduction
 
JavaScript Unit Testing with Jasmine
JavaScript Unit Testing with JasmineJavaScript Unit Testing with Jasmine
JavaScript Unit Testing with Jasmine
 
AngularJS Compile Process
AngularJS Compile ProcessAngularJS Compile Process
AngularJS Compile Process
 
Introduzione JQuery
Introduzione JQueryIntroduzione JQuery
Introduzione JQuery
 
Why Every Tester Should Learn Ruby
Why Every Tester Should Learn RubyWhy Every Tester Should Learn Ruby
Why Every Tester Should Learn Ruby
 
Hidden Treasures in Project Wonder
Hidden Treasures in Project WonderHidden Treasures in Project Wonder
Hidden Treasures in Project Wonder
 
Desenvolvendo APIs usando Rails - Guru SC 2012
Desenvolvendo APIs usando Rails - Guru SC 2012Desenvolvendo APIs usando Rails - Guru SC 2012
Desenvolvendo APIs usando Rails - Guru SC 2012
 
Testing your javascript code with jasmine
Testing your javascript code with jasmineTesting your javascript code with jasmine
Testing your javascript code with jasmine
 
Doctrine 2
Doctrine 2Doctrine 2
Doctrine 2
 
Learning jQuery in 30 minutes
Learning jQuery in 30 minutesLearning jQuery in 30 minutes
Learning jQuery in 30 minutes
 
Filtering data with D2W
Filtering data with D2W Filtering data with D2W
Filtering data with D2W
 
Venturing Into The Wild: A .NET Developer's Experience As A Ruby Developer
Venturing Into The Wild: A .NET Developer's Experience As A Ruby DeveloperVenturing Into The Wild: A .NET Developer's Experience As A Ruby Developer
Venturing Into The Wild: A .NET Developer's Experience As A Ruby Developer
 
jQuery in 15 minutes
jQuery in 15 minutesjQuery in 15 minutes
jQuery in 15 minutes
 

Viewers also liked (9)

test
testtest
test
 
MARUNOUCHI HOUSE
MARUNOUCHI HOUSEMARUNOUCHI HOUSE
MARUNOUCHI HOUSE
 
1 week
1 week1 week
1 week
 
First Week
First WeekFirst Week
First Week
 
2 week
2 week2 week
2 week
 
atalaya
atalayaatalaya
atalaya
 
activitie of first week
activitie of first weekactivitie of first week
activitie of first week
 
3 week
3 week3 week
3 week
 
4 Week
4 Week4 Week
4 Week
 

Similar to Contagion的Ruby/Rails投影片

Propel sfugmd
Propel sfugmdPropel sfugmd
Propel sfugmd
iKlaus
 
Taming that client side mess with Backbone.js
Taming that client side mess with Backbone.jsTaming that client side mess with Backbone.js
Taming that client side mess with Backbone.js
Jarod Ferguson
 
Gail villanueva add muscle to your wordpress site
Gail villanueva   add muscle to your wordpress siteGail villanueva   add muscle to your wordpress site
Gail villanueva add muscle to your wordpress site
references
 
Fast Web Applications Development with Ruby on Rails on Oracle
Fast Web Applications Development with Ruby on Rails on OracleFast Web Applications Development with Ruby on Rails on Oracle
Fast Web Applications Development with Ruby on Rails on Oracle
Raimonds Simanovskis
 

Similar to Contagion的Ruby/Rails投影片 (20)

IndexedDB - Querying and Performance
IndexedDB - Querying and PerformanceIndexedDB - Querying and Performance
IndexedDB - Querying and Performance
 
Propel sfugmd
Propel sfugmdPropel sfugmd
Propel sfugmd
 
Taming that client side mess with Backbone.js
Taming that client side mess with Backbone.jsTaming that client side mess with Backbone.js
Taming that client side mess with Backbone.js
 
Javascript first-class citizenery
Javascript first-class citizeneryJavascript first-class citizenery
Javascript first-class citizenery
 
Introduction to Zend Framework web services
Introduction to Zend Framework web servicesIntroduction to Zend Framework web services
Introduction to Zend Framework web services
 
Introduction to Active Record at MySQL Conference 2007
Introduction to Active Record at MySQL Conference 2007Introduction to Active Record at MySQL Conference 2007
Introduction to Active Record at MySQL Conference 2007
 
Fatc
FatcFatc
Fatc
 
Understanding backbonejs
Understanding backbonejsUnderstanding backbonejs
Understanding backbonejs
 
Spring Data for KSDG 2012/09
Spring Data for KSDG 2012/09Spring Data for KSDG 2012/09
Spring Data for KSDG 2012/09
 
Future of Web Apps: Google Gears
Future of Web Apps: Google GearsFuture of Web Apps: Google Gears
Future of Web Apps: Google Gears
 
Agile data presentation 3 - cambridge
Agile data   presentation 3 - cambridgeAgile data   presentation 3 - cambridge
Agile data presentation 3 - cambridge
 
Zend framework service
Zend framework serviceZend framework service
Zend framework service
 
Zend framework service
Zend framework serviceZend framework service
Zend framework service
 
Scaling php applications with redis
Scaling php applications with redisScaling php applications with redis
Scaling php applications with redis
 
PHPSpec - the only Design Tool you need - 4Developers
PHPSpec - the only Design Tool you need - 4DevelopersPHPSpec - the only Design Tool you need - 4Developers
PHPSpec - the only Design Tool you need - 4Developers
 
Rapid Prototyping with PEAR
Rapid Prototyping with PEARRapid Prototyping with PEAR
Rapid Prototyping with PEAR
 
GraphQL - when REST API is not enough - lessons learned
GraphQL - when REST API is not enough - lessons learnedGraphQL - when REST API is not enough - lessons learned
GraphQL - when REST API is not enough - lessons learned
 
Backbone.js — Introduction to client-side JavaScript MVC
Backbone.js — Introduction to client-side JavaScript MVCBackbone.js — Introduction to client-side JavaScript MVC
Backbone.js — Introduction to client-side JavaScript MVC
 
Gail villanueva add muscle to your wordpress site
Gail villanueva   add muscle to your wordpress siteGail villanueva   add muscle to your wordpress site
Gail villanueva add muscle to your wordpress site
 
Fast Web Applications Development with Ruby on Rails on Oracle
Fast Web Applications Development with Ruby on Rails on OracleFast Web Applications Development with Ruby on Rails on Oracle
Fast Web Applications Development with Ruby on Rails on Oracle
 

Recently uploaded

EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
Earley Information Science
 

Recently uploaded (20)

GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 

Contagion的Ruby/Rails投影片

  • 1. RUBY on OSDC.TW 2006
  • 4. 450,000 over 400,000 downloads 337,500 225,000 112,500 0 2004 July 2004 Dec. 2005 Oct. 2006 April
  • 5. 400 seats, sold out in one week • extra 150 seats, sold out in 24 hours
  • 7.
  • 8.
  • 9. Data from BookScan: Ruby Books sales is up 1,552% over last year.
  • 10.
  • 11. RoR is so HOT Everybody wants to clone it
  • 12.
  • 14. Ruby on Rails is an open-source web framework
  • 16. What Makes Programmer Happy? • Simplicity • Well organized • Easy to learn • Easy to Maintain • Easy to Write
  • 17. SIMPLE Easy to Learn and Write No separation between Business Logic and Display Logic
  • 18. Corporate Approval Well Structured Steep Learn Curve Complex Configuration No fast turnaround
  • 19. Finding the middle ground with
  • 22. One Language - Ruby • Model - View - Controller • Database Schema generation • Javascript generation • XML generation • Makefile
  • 23. Convention Over Configuration
  • 24. CREATE TABLE orders ( id INTEGER PRIMARY KEY AUTO_INCREMENT, An order_date TIMESTAMP NOT NULL, price_total DOUBLE NOT NULL ); example CREATE TABLE products ( id INTEGER PRIMARY KEY AUTO_INCREMENT, from a name VARCHAR(80) NOT NULL, price DOUBLE NOT NULL ); Hibernate CREATE TABLE order_items ( id INTEGER PRIMARY KEY AUTO_INCREMENT, tutorial order_id INTEGER NOT NULL, product_id INTEGER NOT NULL, amount INTEGER NOT NULL, price DOUBLE NOT NULL );
  • 25. public class Order Java { private Integer id; private Date date; private double priceTotal; Object private Set orderItems = new HashSet(); public Order() { Model: this.date = new Date(); } public Integer getId() { Order return id; } public void setId(Integer id) { this.id = id; } public Date getDate() { return date; } public void setDate(date) { this.date = date; } public void addProduct(Product p, int amount) { OrderItem orderItem = new OrderItem(this, p, amount); this.priceTotal = this.priceTotal + p.getPrice() * amount; this.orderItems.add(orderItem); } }
  • 26. <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD//EN" "http://hibernate.sourceforge.net/hibernate-mapping-2.0.dtd"> Java <hibernate-mapping> <class name="test.hibernate.Order" table="orders"> <id name="id" type="string" unsaved-value="null" > <column name="id" sql-type="integer" not-null="true"/> Database <generator class="native"/> </id> <property name="date"> Mapping: <column name="order_date" sql-type="datetime" not-null="true"/> </property> Order <property name="priceTotal"> <column name="price_total" sql-type="double" not-null="true"/> </property> <set name="orderItems" table="order_items" inverse="true" cascade="all"> <key column="order_id" /> <one-to-many class="test.hibernate.OrderItem" /> </set> </class> </hibernate-mapping>
  • 27. Rails Data Model: Order class Order < ActiveRecord::Base has_many :order_items def add_product(product, amount) order_item = OrderItem.new(product, amount) self.price_total += product.price * amount order_items << order_item end end
  • 28. "opinionated software" — sacrificing some flexibility in favour of simplicity
  • 29. “much greater productivity and a better developer experience”
  • 30.
  • 31. Dispatch based on URLs http://myapp/orders/show/1 Application controller action id *customizable by Routing
  • 32. Action grouped in Controller class OrdersController < ApplicationController def index list # Default to app/views/orders/index.rhtml render :action => 'list' end def list @order_pages, @orders = paginate :orders, :per_page => 10 end def show @order = Order.find(params[:id]) end end
  • 33. Rendering and Redirection def update @order = Order.find(params[:id]) if @order.update_attributes(params[:order]) flash[:notice] = 'Order was successfully updated.' redirect_to :action => 'show', :id => @order else render :action => 'edit' end end
  • 34. Query Data the_order = Order.find(2) book = Product.find_by_name(”Programming Ruby”) small_order = Order.find :first, :condition => [”price_total <= ?”, 50.0] web_books = Product.find :all, :condition => [”name like ?”,”%Web%”] print book.name print the_order.price_total
  • 35. Associations class Order < ActiveRecord::Base has_many :order_items end the_order = Order.find :first the_oder.oder_items.each do |item| print item.name end * Some other associations: has_one, belongs_to, has_and_belongs_to_many...
  • 36. Validations class Product < ActiveRecord::Base validates_presenc_of :name validtaes_numericality :price end Hooks class Order < ActiveRecord::Base def before_destory order_items.destory_all end end
  • 37. Views - Erb <!-- app/views/product/list.rhtml --> <% for product in @products -%> <p> <ul> <li> name: <%= product.name %> </li> <li> price: <%= product.price %> </li> </ul> <%= link_to 'Show', :action => 'show', :id => product %> </p> <% end -%>
  • 38. Sounds Great !! But it is written in .... ?? Ruby ??
  • 39. Rails makes it fast to develop, but the true power behind Rails is RUBY
  • 40. Blocks • Iteration 5.times { |i| puts i } [1,2,3].each { |i| puts i } • Resource Management File.open(’t.txt’) do |f| #do something end • Callback TkButton.new do text “EXIT” command { exit} end
  • 41. New Language Construct Rakefile task :test => [:compile, :dataLoad] do # run the tests end Markaby html do body do h1 ‘Hello World’ end end
  • 42. Dynamic Nature •Open Class • Runtime Definition • Code Evaluation • Hooks
  • 43. Meta - Programming class Order < ActiveRecord::Base has_many :order_items end class Product < ActiveRecord::Base validates_presenc_of :name validtaes_numericality :price end
  • 44. Syntax Matters • Succinct • Easy to Read • Principle of Least Surprise
  • 45. Ruby is designed to make programmers Happy
  • 46. Where Rails Sucks •Internationalization • Speed • Template System • Stability • Legacy System
  • 47. Lack Resources In Taiwan
  • 49. Q&A