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
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"
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
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
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
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
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