Intro to Ruby and
Rails
By Mark Menard
Enable Labs
What is a dynamic language?

 “…a class of high-level programming languages that
 execute at runtime many common behaviors that other
 languages might perform during compilation, if at all.
 These behaviors could include extension of the
 program, by adding new code, by extending objects and
 definitions, or by modifying the type system, all during
 program execution.”

 -Dynamic Programming Languages from Wikipedia
Examples of Dynamic Languages
Lisp
Scheme
Smalltalk
Perl
Lua
PHP
Javascript
Groovy
Ruby
Python


                                3
Dynamic vs. Static

Dynamic Languages                                Static Languages
Variable types do not have to be specified.      Variable types generally have to be specified.

Class definitions can be modified at run time.   Class definitions are frozen at time of
                                                 specification.

Standard library can be augmented.               Standard library is frozen.


Generally terse.                                 Generally more verbose.
Frequently used for scripting.                   Generally not used for scripting.
Usually aren’t compiled.                         Generally are compiled.
Commonly run on a Virtual Machine. Some are      Can run on a VM or on bare metal.
interpreted.

Typically support reflection.                    Can support reflection.
Intro to Ruby

Dynamic Object Oriented        Closures
 Language                       Literal arrays, hashes and
 Everything is an object        regexes
Duck typed                     Operator overloading
Has open classes               Runs on Windows, Linux, *nix,
Uses dynamic method dispatch    OS X, Java, and .Net
Supports method_missing
 functionality
Support meta-programming
Executable Class Definitions
REPL
Mixins
Everything is an expression
Scripting
Many dynamic languages are easily at home scripting.
Allows easy proof of concept before committing to a large project.
Can be used for many system administration needs.
 Full power of a multi-purpose language.




                                                                      6
Terse / Low Ceremony
Ruby uses unchecked exceptions.
 No more try…catch…finally blocks everyplace.
 No more throws statements.
Cleaner syntax.
No type declarations.
See the solution not the noise.




                                                 7
REPL: irb
Access to the entire language and functionality in an interactive
 environment.
Prototype new functionality.
Explore functionality of new libraries.
Bug test problems in your code.
Interact with your application while it is running.




                                                                     8
Variables
Do not need to be declared, just use it and it springs into existence.
 Instance variables start with @ (ie: @name)
  Method variables are just the name (ie: name = )
 Class variables start with @@ (ie: @@class_var = 1)




                                                                     9
Literal Arrays, Hashes and Regex in Ruby

# Create an array
array = [ 1, 2, 3, 4, 5 ]
puts array.inspect
# Create a hash
hash = { :a => 'a', :b => 'b', 1 => 1, "a" => "string a" }
puts hash.inspect
string = "abcd"
puts string =~ /abcd/ ? ”match" : ”no match" #=> ”match"
puts string =~ /dcba/ ? ”match" : ”no match" #=> ”no match"
Classes in Ruby
class Foo
 def do_something
   puts "Foo#do_something"
 end
end

class Bar < Foo
 def do_something
   puts "Bar#do_something"
 end
end
foo = Foo.new
foo.do_something #=> prints Foo#do_something
bar = Bar.new
bar.do_something #=> prints Bar#do_something
Open Classes
Classes are open for modification at runtime.
 Methods can be added.
 Methods can be redefined.
 Methods can be added to an instance.
 Methods can be redefined on an instance.
Allows you to closely adapt the language to your problem domain.
 It’s like sculpting in clay instead of stone.
Mocking and stubbing become trivial.




                                                                    12
Open Classes

class String

  def url_decode
    CGI::unescape(self)
  end


  def url_encode
    CGI::escape(self)
  end

end
Open Classes in Ruby

class Foo
 def escape
   puts "Whee! I'm free!"
 end
end
foo = Foo.new
foo.escape #=> prints "Whee! I'm free!"

class Foo
 def escape
   puts "Not so fast!"
 end
end

foo.escape #=> prints ”Not so fast!"
Mixins in Ruby
module Logging
 def log (msg)
  puts msg
 end
end

class OrderDispatcher
 include Logging

 def dispatch_international_order (order)
  destination = DistinationService.find(order.foreign_party)
  log("Sending #{order.number} to #{destination.name}")

  ...
 end
end
Duck Typing

“If it walks like a duck, quacks like a duck and has feathers then it’s
 a duck.”
Interfaces are conceptual, not actual.
An object’s type is defined by the messages it responds to.
Duck Typing in Ruby
class Cat               end
  def talk            end
    puts "Meow"
  end                 [ Cat.new, Dog.new, Duck.new,
end                   Person.new ].each do |ob|
                        ob.talk
class Dog             end
  def talk
    puts "Woof"
  end
end

class Duck
  def talk
    puts "Quack!"
  end
end
class Person
  def talk
    puts "Hi"
Closures in Ruby

def create_closure (name)

 # Create a closure closing over the scope which contains 'name'
 lambda do |job|
   puts "#{name} has a new job doing #{job}."
 end
end
closure = create_closure("Mark")
closure.call("web development") #=> Mark has a new job doing web development.
closure.call("goat milking") #=> Mark has a new job doing goat milking.
Method Missing in Ruby

class MethodMissing
 def method_missing (name, *args)
   puts "Oops! Method #{name} does not exist."
 end
end
mm = MethodMissing.new
mm.foo #=> prints “Oops! Method foo does not exist.
Metaprogramming in Ruby

class MethodMissing
 def method_missing (name, *args)
   puts "method_missing called the first time."
   puts "Defining #{name} method."
   instance_eval %Q{
     def #{name.to_s} (args)
      puts "Inside the dynamically defined foo method."
     end
   }
   send(name, args)
 end
end
mm = MethodMissing.new
mm.foo(nil)
mm.foo(nil)
Operator Overloading in Ruby
class Person
 def initialize (name)
   @name = name
 end

 def + (other)
  "#{@name} and #{other.to_s} have gotten together"
 end

 def to_s
  @name
 end
end
mark = Person.new("Mark")
sylva = Person.new("Sylva")
puts mark + sylva #=> "Mark and Sylva have gotten together"
Intro to Ruby on
Rails
Ruby Wins!


 “I always knew one day Smalltalk would
 replace Java. I just didn’t know it would be
 called Ruby.”

 - Kent Beck,
   Creator of “Extreme Programming”



                                                23
Ruby on Rails

Ruby on Rails is astounding. Using it is like watching a
kung-fu movie, where a dozen bad-ass frameworks
prepare to beat up the little newcomer only to be
handed their asses in a variety of imaginative ways.

-Nathan Torkington,
O'Reilly Program Chair for OSCON



                                                       24
The Elevator Pitch



 Ruby on Rails is an open-source web framework
 that is optimized for programmer happiness and
 sustainable productivity. It lets you write beautiful
 code by favoring convention over configuration.




                                                         25
Overview
Rails is a full stack web framework
 Model: ActiveRecord
  ORM
  database connectivity
  Database schema management
 View: ActiveView
  View layer
  Templates
 Controller: ActionController
  Web controller framework
  Manages web integration
 Active Support
  Extensions to Ruby to support web development
                                                   26
The Rails Philosophy
Ruby - less and more readable code, shorter development times,
 simple but powerful, no compilation cycle.
Convention over configuration
Predefined directory structure, and naming conventions
Best practices: MVC, DRY, Testing
Almost everything in Rails is Ruby code (SQL and JavaScript are
 abstracted)
Integrated AJAX support.
Web services with REST.
Good community, tools, and documentation
Extracted from a real application: Basecamp

                                                                   27
Rake: The Ruby Make
Rake lets you define a dependency tree of tasks to be executed.
Rake tasks are loaded from the file Rakefile, and other .rake files in
 the source of the project.
Rake automates and simplifies creating and managing the
 development of a Rails project.




                                                                   28
Environments
Rails has support for multiple execution environments.
Environments encapsulate database settings and other
 configuration.
Typical environments
 Development
 Test
 Production
Additional environments are easy to add.




                                                          29
Migrations
Managing Schema
Evolution
Managing Data Schemas
Rails includes support for migrations to manage the evolution of
 your database schema.
 No need to write SQL.
 Migrations use a database independent Ruby API.
 Migrations are Ruby scripts giving you access to the full power of
  the language.




                                                                       31
Typical Migration Tasks
create_table
add_column
change_column
rename_column
rename_table
add_index




                          32
Migration Example
create_table "users", :force => true do |t|
  t.string :login
 t.string :email
 t.string :remember_token
  t.string :salt, :crypted_password, :limit => 40
  t.datetime :remember_token_expires_at
  t.timestamps
end




                                                    33
Active Record
Modeling the World
Fundamentals
One database table maps to one Ruby class
Table names are plural and class names are singular
Database columns map to attributes, i.e. get and set methods, in
 the model class
All tables have an integer primary key called id
Database tables are created with migrations




                                                                    35
Active Record Model Example
create_table "persons" do |t|
  t.string :first_name, last_name
  t.timestamps
end

class Person < ActiveRecord::Base
end

p = Person.new
p.first_name = ‘Mark’
p.last_name = ‘Menard’
p.save




                                    36
CRUD
Create: create, new
Read: find, find_by_<attribute>
Update: save, update_attributes
Delete: destroy




                                   37
Finding Models
User.find(:first)
User.find(:all)
User.find(1)
User.find_by_login(‘mark’)
User.find(:all, :conditions => [ “login = ? AND password = ?”, login,
 password])




                                                                    38
Advanced Finding
:limit
:offset
:order
:joins
:select
:group




                   39
Updating Models
user = User.find(1)
user.first_name = ‘Mark’
user.last_name = ‘Menard’
user.save!




                            40
Transactions
Account.transaction do
  account1.deposit(100)
  account2.withdraw(100)
end




                           41
Active Record
Associations
Joining Things Together
Association Types
Two primary types of associations:
 belongs_to
 has_one / has_many
There are others, but they are not commonly used.




                                                     43
Association Example
# Has Many

class Order < ActiveRecord::Base
  has_many :order_line_items
end

class OrderLineItem < ActiveRecord::Base
  belongs_to :order
end

# Has One

class Party < ActiveRecord::Base
  has_one :login_credential
end

class LoginCredential < ActiveRecord::Base
  belongs_to :party
end
                                             44
Dynamic Association Methods
Associations add methods to the class.
 This is an excellent example of meta-programming.
Added methods allow easy management of the associated models.
 order.order_line_items << line_item
 order.order_line_items.create()




                                                             45
Active Record
Validations
Keeping Your Data Safe
Validations
Validations are rules in your model objects to help protect the
 integrity of your data
Validation is invoked by the save method. Save returns true if
 validations pass and false otherwise.
If you invoke save! then a RecordInvalid exception is raised if the
 object is not valid
Use save(false) if you need to turn off validation




                                                                       47
Validation Call Back Methods
validate
validate_on_create
validate_on_update




                               48
Validation Example
class Person < ActiveRecord::Base
  def validate
    puts “validate invoked”
  end

  def validate_on_create
    puts “validate_on_create invoked”
  end

  def validate_on_update
    puts “validate_on_update invoked”
  end
end

peter = Person.create(:name => “Peter”) # => validate, validate_on_create invoked
peter.last_name = “Forsberg”
peter.save # => validate_on_update invoked




                                                                                    49
Validation Macros
validates_acceptance_of
validate_associated
validates_confirmation_of validates_each
validates_exclusion_of
validates_format_of
validates_inclusion_of
validates_length_of
validates_numericality_of
validates_presence_of
validates_size_of
validates_uniqueness_of
                                            50
Validation Macro Examples
class User < ActiveRecord::Base
  validates_presence_of :name, :email, :password
  validates_format_of :name, :with => /^w+$/,
                      :message => “may only contain word characters”
  validates_uniqueness_of :name, :message => “is already in use”
  validates_length_of :password, :within => 4..40
  validates_confirmation_of :password
  validates_inclusion_of :role, :in => %w(super admin user),
                         :message => “must be super, admin, or user”,
                         :allow_nil => true
  validates_presence_of :customer_id,
                        :if => Proc.new { |u|
                                  %w(admin user).include?(u.role)
                                }
  validates_numericality_of :weight,
                            :only_integer => true,
                            :allow_nil => true
end


                                                                        51
ActionController
The “C” in MVC
Controllers
Controllers are Ruby classes that live under app/ controllers
Controller classes extend ActionController::Base
An action is a public method and/or a corresponding view template




                                                                 53
Rendering a Response
A response is rendered with the render command
An action can only render a response once
Rails invokes render automatically if you don’t
Redirects are made with the redirect_to command




                                                   54
A Simple Controller
class PrioritiesController < InternalController

  def show
    @priority = current_account.priorities.find(params[:id])
  end

  def new
    @priority = Priority.new
  end

  def create
    @priority = Priority.new(params[:priority])
    if @priority.save
      flash[:notice] = 'The priority was successfully created.'
      redirect_to account_url
    else
      render :action => "new"
    end
  end

end                                                               55
Sessions
A hash stored on the server, typically in a database table or on the
 file system.
Keyed by the cookie _session_id
Avoid storing complex Ruby objects, instead put id:s in the session
 and keep data in the database, i.e. use session[:user_id] rather
 than session[:user]




                                                                    56
ActionView
Our Face to the World
ActionView
ActionView is the module in the ActionPack library that deals with
 rendering a response to the client.
The controller decides which template and/or partial and layout to
 use in the response
Templates use helper methods to generate links, forms, and
 JavaScript, and to format text




                                                                      58
Where do templates live?
Templates that belong to a certain controller typically live under
 app/view/controller_name, i.e. templates for
 Admin::UsersController would live under app/ views/admin/users
Templates shared across controllers are put under app/views/
 shared. You can render them with render :template => ‘shared/
 my_template’
You can have templates shared across Rails applications and render
 them with render :file => ‘path/to/template’




                                                                      59
Template Environment
Templates have access to the controller object’s flash, headers,
 logger, params, request, response, and session.
Instance variables (i.e. @variable) in the controller are available in
 templates
The current controller is available as the attribute controller.




                                                                      60
Embedded Ruby
<%= ruby code here %> - Evaluates the Ruby code and prints the
 last evaluated value to the page.
<% ruby code here %> - Evaluates Ruby code without outputting
 anything to the page.




                                                                 61
Example View
<p>
  <b>Name:</b>
  <%=h @category.name %>
</p>



<%= link_to 'Edit', edit_category_path(@category) %>
<%= link_to 'Back', categories_path %>




                                                       62
Haml
#profile
  .left.column                                       Haml
    #date= print_date
    #address= current_user.address                          vs
  .right.column
    #email= current_user.email                                   HTML with ERB
    #bio= current_user.bio



<div id="profile">
  <div class="left column">
    <div id="date"><%= print_date %></div>
    <div id="address"><%= current_user.address %></div>
  </div>
  <div class="right column">
    <div id="email"><%= current_user.email %></div>
    <div id="bio"><%= current_user.bio %></div>
  </div>
</div>
                                                                                 63
Shameless Self
Promotion
We do Ruby on Rails
Development and
Training
Ruby and Rails Training
One day to three day programs.
Introduction to Ruby
Advanced Ruby
Introduction to Rails
Advanced Rails
Test Driven Development
Behavior Driven Development
Test Anything with Cucumber
Advanced Domain Modeling with ActiveRecord
Domain Driven Development with Rails


                                              65
Ruby on Rails Development
Full Life Cycle Project Development
 Inception
 Implementation
 Deployment
 Long Term Support
Ruby on Rails Mentoring
 Get your team up to speed using Rails




                                          66
Want to do Rails professionally?
We’re addicted to the success of our clients.
We’re addicted to quality.
We’re addicted to craftsmanship.
We’re addicted to being the best.

You’re dedicated to life long improvement.
You thrive under a challenge.
You’re a team player.
You work hard to be the best. Not your best. THE BEST.

Do well in the training. It’s an audition.
                                                          67

More Related Content

PDF
Ror Seminar With agilebd.org on 23 Jan09
PDF
Ruby on Rails 101 - Presentation Slides for a Five Day Introductory Course
PDF
O que há de novo no Rails 3
PDF
Security Goodness with Ruby on Rails
PDF
Debugging on rails
PPT
Introduction to Ruby on Rails
PDF
Ruby on Rails 2.1 What's New
PDF
遇見 Ruby on Rails
Ror Seminar With agilebd.org on 23 Jan09
Ruby on Rails 101 - Presentation Slides for a Five Day Introductory Course
O que há de novo no Rails 3
Security Goodness with Ruby on Rails
Debugging on rails
Introduction to Ruby on Rails
Ruby on Rails 2.1 What's New
遇見 Ruby on Rails

What's hot (20)

PPT
Migrating PriceChirp to Rails 3.0: The Pain Points
PDF
Ruby on Rails Presentation
PDF
RoR (Ruby on Rails)
PDF
Ruby On Rails
PDF
Introduction to Rails - presented by Arman Ortega
PDF
How DSL works on Ruby
PPT
Java presentation
KEY
Ruby on Rails survival guide of an aged Java developer
PDF
Ruby - a tester's best friend
PDF
Buildr In Action @devoxx france 2012
PDF
PECL Picks - Extensions to make your life better
PDF
An introduction to the ruby ecosystem
PDF
JCR - Java Content Repositories
PPT
Java, Ruby & Rails
PDF
DataMapper on Infinispan
PDF
Workin On The Rails Road
PDF
Till Vollmer Presentation
PPTX
Ruby on Rails All Hands Meeting
PDF
Middleware as Code with mruby
PPTX
Introduction to Ruby on Rails
Migrating PriceChirp to Rails 3.0: The Pain Points
Ruby on Rails Presentation
RoR (Ruby on Rails)
Ruby On Rails
Introduction to Rails - presented by Arman Ortega
How DSL works on Ruby
Java presentation
Ruby on Rails survival guide of an aged Java developer
Ruby - a tester's best friend
Buildr In Action @devoxx france 2012
PECL Picks - Extensions to make your life better
An introduction to the ruby ecosystem
JCR - Java Content Repositories
Java, Ruby & Rails
DataMapper on Infinispan
Workin On The Rails Road
Till Vollmer Presentation
Ruby on Rails All Hands Meeting
Middleware as Code with mruby
Introduction to Ruby on Rails
Ad

Viewers also liked (10)

KEY
Rails 3 generators
PDF
Ruby on Rails 101
PDF
PDF
Rails Text Mate Cheats
PPTX
Rest and Rails
PDF
Ruby on Rails Kickstart 103 & 104
PDF
Railsguide
PDF
Rails 3 Beginner to Builder 2011 Week 3
KEY
Introducing Command Line Applications with Ruby
PDF
Ruby on Rails for beginners
Rails 3 generators
Ruby on Rails 101
Rails Text Mate Cheats
Rest and Rails
Ruby on Rails Kickstart 103 & 104
Railsguide
Rails 3 Beginner to Builder 2011 Week 3
Introducing Command Line Applications with Ruby
Ruby on Rails for beginners
Ad

Similar to Ruby on Rails Training - Module 1 (20)

KEY
Introduction to Ruby
PDF
Ruby Metaprogramming 08
PPT
Workin ontherailsroad
PPT
WorkinOnTheRailsRoad
PDF
Ruby On Rails Introduction
PDF
Bhavesh ro r
PPT
Ruby on rails
PPT
Ruby on rails
PPT
Ruby on rails
PPT
Ruby on Rails
PPTX
Why Ruby?
ODP
PDF
Ruby on Rails Presentation
PDF
Ruby on Rails (RoR) as a back-end processor for Apex
PPTX
Ruby on rails for beginers
PPTX
Rubyonrails 120409061835-phpapp02
PPTX
Ruby on Rails Introduction M&P - IT Skill Development Program 07
PPTX
Ruby on Rails - An overview
PDF
The Joy Of Ruby
PPT
Introduction to Ruby
Ruby Metaprogramming 08
Workin ontherailsroad
WorkinOnTheRailsRoad
Ruby On Rails Introduction
Bhavesh ro r
Ruby on rails
Ruby on rails
Ruby on rails
Ruby on Rails
Why Ruby?
Ruby on Rails Presentation
Ruby on Rails (RoR) as a back-end processor for Apex
Ruby on rails for beginers
Rubyonrails 120409061835-phpapp02
Ruby on Rails Introduction M&P - IT Skill Development Program 07
Ruby on Rails - An overview
The Joy Of Ruby

More from Mark Menard (14)

PDF
Let's Do Some Upfront Design - WindyCityRails 2014
PDF
A Tour of Wyriki
PDF
Small Code - RailsConf 2014
PDF
Small Code - Ruby on Ales 2014
PDF
Write Small Things (Code)
PDF
JRuby 6 Years in Production
PDF
Conference of Grand Masters Tech Talk 2013
KEY
Startup Lessons Learned
PDF
Mobile Platforms and App Development
KEY
Ruby on Rails Training - Module 2
PPT
Intro to Rails ActiveRecord
PPT
Behavior Driven Development with Rails
PPT
Intro to Ruby on Rails
PPT
JRuby in a Java World
Let's Do Some Upfront Design - WindyCityRails 2014
A Tour of Wyriki
Small Code - RailsConf 2014
Small Code - Ruby on Ales 2014
Write Small Things (Code)
JRuby 6 Years in Production
Conference of Grand Masters Tech Talk 2013
Startup Lessons Learned
Mobile Platforms and App Development
Ruby on Rails Training - Module 2
Intro to Rails ActiveRecord
Behavior Driven Development with Rails
Intro to Ruby on Rails
JRuby in a Java World

Recently uploaded (20)

PDF
【AI論文解説】高速・高品質な生成を実現するFlow Map Models(Part 1~3)
PPTX
Blending method and technology for hydrogen.pptx
PDF
The Basics of Artificial Intelligence - Understanding the Key Concepts and Te...
PDF
TrustArc Webinar - Data Minimization in Practice_ Reducing Risk, Enhancing Co...
PDF
GDG Cloud Southlake #45: Patrick Debois: The Impact of GenAI on Development a...
PPTX
Presentation - Principles of Instructional Design.pptx
PDF
Optimizing bioinformatics applications: a novel approach with human protein d...
PDF
ELLIE29.pdfWETWETAWTAWETAETAETERTRTERTER
PDF
Revolutionizing recommendations a survey: a comprehensive exploration of mode...
PDF
FASHION-DRIVEN TEXTILES AS A CRYSTAL OF A NEW STREAM FOR STAKEHOLDER CAPITALI...
PDF
State of AI in Business 2025 - MIT NANDA
PDF
Altius execution marketplace concept.pdf
PDF
Child-friendly e-learning for artificial intelligence education in Indonesia:...
PDF
TicketRoot: Event Tech Solutions Deck 2025
PDF
Rooftops detection with YOLOv8 from aerial imagery and a brief review on roof...
PDF
Be ready for tomorrow’s needs with a longer-lasting, higher-performing PC
PPTX
Slides World Game (s) Great Redesign Eco Economic Epochs.pptx
PDF
Applying Agentic AI in Enterprise Automation
PDF
EGCB_Solar_Project_Presentation_and Finalcial Analysis.pdf
PDF
Advancements in abstractive text summarization: a deep learning approach
【AI論文解説】高速・高品質な生成を実現するFlow Map Models(Part 1~3)
Blending method and technology for hydrogen.pptx
The Basics of Artificial Intelligence - Understanding the Key Concepts and Te...
TrustArc Webinar - Data Minimization in Practice_ Reducing Risk, Enhancing Co...
GDG Cloud Southlake #45: Patrick Debois: The Impact of GenAI on Development a...
Presentation - Principles of Instructional Design.pptx
Optimizing bioinformatics applications: a novel approach with human protein d...
ELLIE29.pdfWETWETAWTAWETAETAETERTRTERTER
Revolutionizing recommendations a survey: a comprehensive exploration of mode...
FASHION-DRIVEN TEXTILES AS A CRYSTAL OF A NEW STREAM FOR STAKEHOLDER CAPITALI...
State of AI in Business 2025 - MIT NANDA
Altius execution marketplace concept.pdf
Child-friendly e-learning for artificial intelligence education in Indonesia:...
TicketRoot: Event Tech Solutions Deck 2025
Rooftops detection with YOLOv8 from aerial imagery and a brief review on roof...
Be ready for tomorrow’s needs with a longer-lasting, higher-performing PC
Slides World Game (s) Great Redesign Eco Economic Epochs.pptx
Applying Agentic AI in Enterprise Automation
EGCB_Solar_Project_Presentation_and Finalcial Analysis.pdf
Advancements in abstractive text summarization: a deep learning approach

Ruby on Rails Training - Module 1

  • 1. Intro to Ruby and Rails By Mark Menard Enable Labs
  • 2. What is a dynamic language? “…a class of high-level programming languages that execute at runtime many common behaviors that other languages might perform during compilation, if at all. These behaviors could include extension of the program, by adding new code, by extending objects and definitions, or by modifying the type system, all during program execution.” -Dynamic Programming Languages from Wikipedia
  • 3. Examples of Dynamic Languages Lisp Scheme Smalltalk Perl Lua PHP Javascript Groovy Ruby Python 3
  • 4. Dynamic vs. Static Dynamic Languages Static Languages Variable types do not have to be specified. Variable types generally have to be specified. Class definitions can be modified at run time. Class definitions are frozen at time of specification. Standard library can be augmented. Standard library is frozen. Generally terse. Generally more verbose. Frequently used for scripting. Generally not used for scripting. Usually aren’t compiled. Generally are compiled. Commonly run on a Virtual Machine. Some are Can run on a VM or on bare metal. interpreted. Typically support reflection. Can support reflection.
  • 5. Intro to Ruby Dynamic Object Oriented Closures Language Literal arrays, hashes and Everything is an object regexes Duck typed Operator overloading Has open classes Runs on Windows, Linux, *nix, Uses dynamic method dispatch OS X, Java, and .Net Supports method_missing functionality Support meta-programming Executable Class Definitions REPL Mixins Everything is an expression
  • 6. Scripting Many dynamic languages are easily at home scripting. Allows easy proof of concept before committing to a large project. Can be used for many system administration needs. Full power of a multi-purpose language. 6
  • 7. Terse / Low Ceremony Ruby uses unchecked exceptions. No more try…catch…finally blocks everyplace. No more throws statements. Cleaner syntax. No type declarations. See the solution not the noise. 7
  • 8. REPL: irb Access to the entire language and functionality in an interactive environment. Prototype new functionality. Explore functionality of new libraries. Bug test problems in your code. Interact with your application while it is running. 8
  • 9. Variables Do not need to be declared, just use it and it springs into existence. Instance variables start with @ (ie: @name) Method variables are just the name (ie: name = ) Class variables start with @@ (ie: @@class_var = 1) 9
  • 10. Literal Arrays, Hashes and Regex in Ruby # Create an array array = [ 1, 2, 3, 4, 5 ] puts array.inspect # Create a hash hash = { :a => 'a', :b => 'b', 1 => 1, "a" => "string a" } puts hash.inspect string = "abcd" puts string =~ /abcd/ ? ”match" : ”no match" #=> ”match" puts string =~ /dcba/ ? ”match" : ”no match" #=> ”no match"
  • 11. Classes in Ruby class Foo def do_something puts "Foo#do_something" end end class Bar < Foo def do_something puts "Bar#do_something" end end foo = Foo.new foo.do_something #=> prints Foo#do_something bar = Bar.new bar.do_something #=> prints Bar#do_something
  • 12. Open Classes Classes are open for modification at runtime. Methods can be added. Methods can be redefined. Methods can be added to an instance. Methods can be redefined on an instance. Allows you to closely adapt the language to your problem domain. It’s like sculpting in clay instead of stone. Mocking and stubbing become trivial. 12
  • 13. Open Classes class String def url_decode CGI::unescape(self) end def url_encode CGI::escape(self) end end
  • 14. Open Classes in Ruby class Foo def escape puts "Whee! I'm free!" end end foo = Foo.new foo.escape #=> prints "Whee! I'm free!" class Foo def escape puts "Not so fast!" end end foo.escape #=> prints ”Not so fast!"
  • 15. Mixins in Ruby module Logging def log (msg) puts msg end end class OrderDispatcher include Logging def dispatch_international_order (order) destination = DistinationService.find(order.foreign_party) log("Sending #{order.number} to #{destination.name}") ... end end
  • 16. Duck Typing “If it walks like a duck, quacks like a duck and has feathers then it’s a duck.” Interfaces are conceptual, not actual. An object’s type is defined by the messages it responds to.
  • 17. Duck Typing in Ruby class Cat end def talk end puts "Meow" end [ Cat.new, Dog.new, Duck.new, end Person.new ].each do |ob| ob.talk class Dog end def talk puts "Woof" end end class Duck def talk puts "Quack!" end end class Person def talk puts "Hi"
  • 18. Closures in Ruby def create_closure (name) # Create a closure closing over the scope which contains 'name' lambda do |job| puts "#{name} has a new job doing #{job}." end end closure = create_closure("Mark") closure.call("web development") #=> Mark has a new job doing web development. closure.call("goat milking") #=> Mark has a new job doing goat milking.
  • 19. Method Missing in Ruby class MethodMissing def method_missing (name, *args) puts "Oops! Method #{name} does not exist." end end mm = MethodMissing.new mm.foo #=> prints “Oops! Method foo does not exist.
  • 20. Metaprogramming in Ruby class MethodMissing def method_missing (name, *args) puts "method_missing called the first time." puts "Defining #{name} method." instance_eval %Q{ def #{name.to_s} (args) puts "Inside the dynamically defined foo method." end } send(name, args) end end mm = MethodMissing.new mm.foo(nil) mm.foo(nil)
  • 21. Operator Overloading in Ruby class Person def initialize (name) @name = name end def + (other) "#{@name} and #{other.to_s} have gotten together" end def to_s @name end end mark = Person.new("Mark") sylva = Person.new("Sylva") puts mark + sylva #=> "Mark and Sylva have gotten together"
  • 22. Intro to Ruby on Rails
  • 23. Ruby Wins! “I always knew one day Smalltalk would replace Java. I just didn’t know it would be called Ruby.” - Kent Beck, Creator of “Extreme Programming” 23
  • 24. Ruby on Rails Ruby on Rails is astounding. Using it is like watching a kung-fu movie, where a dozen bad-ass frameworks prepare to beat up the little newcomer only to be handed their asses in a variety of imaginative ways. -Nathan Torkington, O'Reilly Program Chair for OSCON 24
  • 25. The Elevator Pitch Ruby on Rails is an open-source web framework that is optimized for programmer happiness and sustainable productivity. It lets you write beautiful code by favoring convention over configuration. 25
  • 26. Overview Rails is a full stack web framework Model: ActiveRecord ORM database connectivity Database schema management View: ActiveView View layer Templates Controller: ActionController Web controller framework Manages web integration Active Support Extensions to Ruby to support web development 26
  • 27. The Rails Philosophy Ruby - less and more readable code, shorter development times, simple but powerful, no compilation cycle. Convention over configuration Predefined directory structure, and naming conventions Best practices: MVC, DRY, Testing Almost everything in Rails is Ruby code (SQL and JavaScript are abstracted) Integrated AJAX support. Web services with REST. Good community, tools, and documentation Extracted from a real application: Basecamp 27
  • 28. Rake: The Ruby Make Rake lets you define a dependency tree of tasks to be executed. Rake tasks are loaded from the file Rakefile, and other .rake files in the source of the project. Rake automates and simplifies creating and managing the development of a Rails project. 28
  • 29. Environments Rails has support for multiple execution environments. Environments encapsulate database settings and other configuration. Typical environments Development Test Production Additional environments are easy to add. 29
  • 31. Managing Data Schemas Rails includes support for migrations to manage the evolution of your database schema. No need to write SQL. Migrations use a database independent Ruby API. Migrations are Ruby scripts giving you access to the full power of the language. 31
  • 33. Migration Example create_table "users", :force => true do |t| t.string :login t.string :email t.string :remember_token t.string :salt, :crypted_password, :limit => 40 t.datetime :remember_token_expires_at t.timestamps end 33
  • 35. Fundamentals One database table maps to one Ruby class Table names are plural and class names are singular Database columns map to attributes, i.e. get and set methods, in the model class All tables have an integer primary key called id Database tables are created with migrations 35
  • 36. Active Record Model Example create_table "persons" do |t| t.string :first_name, last_name t.timestamps end class Person < ActiveRecord::Base end p = Person.new p.first_name = ‘Mark’ p.last_name = ‘Menard’ p.save 36
  • 37. CRUD Create: create, new Read: find, find_by_<attribute> Update: save, update_attributes Delete: destroy 37
  • 40. Updating Models user = User.find(1) user.first_name = ‘Mark’ user.last_name = ‘Menard’ user.save! 40
  • 41. Transactions Account.transaction do account1.deposit(100) account2.withdraw(100) end 41
  • 43. Association Types Two primary types of associations: belongs_to has_one / has_many There are others, but they are not commonly used. 43
  • 44. Association Example # Has Many class Order < ActiveRecord::Base has_many :order_line_items end class OrderLineItem < ActiveRecord::Base belongs_to :order end # Has One class Party < ActiveRecord::Base has_one :login_credential end class LoginCredential < ActiveRecord::Base belongs_to :party end 44
  • 45. Dynamic Association Methods Associations add methods to the class. This is an excellent example of meta-programming. Added methods allow easy management of the associated models. order.order_line_items << line_item order.order_line_items.create() 45
  • 47. Validations Validations are rules in your model objects to help protect the integrity of your data Validation is invoked by the save method. Save returns true if validations pass and false otherwise. If you invoke save! then a RecordInvalid exception is raised if the object is not valid Use save(false) if you need to turn off validation 47
  • 48. Validation Call Back Methods validate validate_on_create validate_on_update 48
  • 49. Validation Example class Person < ActiveRecord::Base def validate puts “validate invoked” end def validate_on_create puts “validate_on_create invoked” end def validate_on_update puts “validate_on_update invoked” end end peter = Person.create(:name => “Peter”) # => validate, validate_on_create invoked peter.last_name = “Forsberg” peter.save # => validate_on_update invoked 49
  • 51. Validation Macro Examples class User < ActiveRecord::Base validates_presence_of :name, :email, :password validates_format_of :name, :with => /^w+$/, :message => “may only contain word characters” validates_uniqueness_of :name, :message => “is already in use” validates_length_of :password, :within => 4..40 validates_confirmation_of :password validates_inclusion_of :role, :in => %w(super admin user), :message => “must be super, admin, or user”, :allow_nil => true validates_presence_of :customer_id, :if => Proc.new { |u| %w(admin user).include?(u.role) } validates_numericality_of :weight, :only_integer => true, :allow_nil => true end 51
  • 53. Controllers Controllers are Ruby classes that live under app/ controllers Controller classes extend ActionController::Base An action is a public method and/or a corresponding view template 53
  • 54. Rendering a Response A response is rendered with the render command An action can only render a response once Rails invokes render automatically if you don’t Redirects are made with the redirect_to command 54
  • 55. A Simple Controller class PrioritiesController < InternalController def show @priority = current_account.priorities.find(params[:id]) end def new @priority = Priority.new end def create @priority = Priority.new(params[:priority]) if @priority.save flash[:notice] = 'The priority was successfully created.' redirect_to account_url else render :action => "new" end end end 55
  • 56. Sessions A hash stored on the server, typically in a database table or on the file system. Keyed by the cookie _session_id Avoid storing complex Ruby objects, instead put id:s in the session and keep data in the database, i.e. use session[:user_id] rather than session[:user] 56
  • 58. ActionView ActionView is the module in the ActionPack library that deals with rendering a response to the client. The controller decides which template and/or partial and layout to use in the response Templates use helper methods to generate links, forms, and JavaScript, and to format text 58
  • 59. Where do templates live? Templates that belong to a certain controller typically live under app/view/controller_name, i.e. templates for Admin::UsersController would live under app/ views/admin/users Templates shared across controllers are put under app/views/ shared. You can render them with render :template => ‘shared/ my_template’ You can have templates shared across Rails applications and render them with render :file => ‘path/to/template’ 59
  • 60. Template Environment Templates have access to the controller object’s flash, headers, logger, params, request, response, and session. Instance variables (i.e. @variable) in the controller are available in templates The current controller is available as the attribute controller. 60
  • 61. Embedded Ruby <%= ruby code here %> - Evaluates the Ruby code and prints the last evaluated value to the page. <% ruby code here %> - Evaluates Ruby code without outputting anything to the page. 61
  • 62. Example View <p> <b>Name:</b> <%=h @category.name %> </p> <%= link_to 'Edit', edit_category_path(@category) %> <%= link_to 'Back', categories_path %> 62
  • 63. Haml #profile .left.column Haml #date= print_date #address= current_user.address vs .right.column #email= current_user.email HTML with ERB #bio= current_user.bio <div id="profile"> <div class="left column"> <div id="date"><%= print_date %></div> <div id="address"><%= current_user.address %></div> </div> <div class="right column"> <div id="email"><%= current_user.email %></div> <div id="bio"><%= current_user.bio %></div> </div> </div> 63
  • 64. Shameless Self Promotion We do Ruby on Rails Development and Training
  • 65. Ruby and Rails Training One day to three day programs. Introduction to Ruby Advanced Ruby Introduction to Rails Advanced Rails Test Driven Development Behavior Driven Development Test Anything with Cucumber Advanced Domain Modeling with ActiveRecord Domain Driven Development with Rails 65
  • 66. Ruby on Rails Development Full Life Cycle Project Development Inception Implementation Deployment Long Term Support Ruby on Rails Mentoring Get your team up to speed using Rails 66
  • 67. Want to do Rails professionally? We’re addicted to the success of our clients. We’re addicted to quality. We’re addicted to craftsmanship. We’re addicted to being the best. You’re dedicated to life long improvement. You thrive under a challenge. You’re a team player. You work hard to be the best. Not your best. THE BEST. Do well in the training. It’s an audition. 67

Editor's Notes