SlideShare a Scribd company logo
1 of 67
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

What's hot

Migrating PriceChirp to Rails 3.0: The Pain Points
Migrating PriceChirp to Rails 3.0: The Pain PointsMigrating PriceChirp to Rails 3.0: The Pain Points
Migrating PriceChirp to Rails 3.0: The Pain PointsSteven Evatt
 
Ruby on Rails Presentation
Ruby on Rails PresentationRuby on Rails Presentation
Ruby on Rails PresentationJoost Hietbrink
 
RoR (Ruby on Rails)
RoR (Ruby on Rails)RoR (Ruby on Rails)
RoR (Ruby on Rails)scandiweb
 
Ruby On Rails
Ruby On RailsRuby On Rails
Ruby On Railsousli07
 
Introduction to Rails - presented by Arman Ortega
Introduction to Rails - presented by Arman OrtegaIntroduction to Rails - presented by Arman Ortega
Introduction to Rails - presented by Arman Ortegaarman o
 
Ruby on Rails survival guide of an aged Java developer
Ruby on Rails survival guide of an aged Java developerRuby on Rails survival guide of an aged Java developer
Ruby on Rails survival guide of an aged Java developergicappa
 
Ruby - a tester's best friend
Ruby - a tester's best friendRuby - a tester's best friend
Ruby - a tester's best friendPeter Lind
 
Buildr In Action @devoxx france 2012
Buildr In Action @devoxx france 2012Buildr In Action @devoxx france 2012
Buildr In Action @devoxx france 2012alexismidon
 
PECL Picks - Extensions to make your life better
PECL Picks - Extensions to make your life betterPECL Picks - Extensions to make your life better
PECL Picks - Extensions to make your life betterZendCon
 
An introduction to the ruby ecosystem
An introduction to the ruby ecosystemAn introduction to the ruby ecosystem
An introduction to the ruby ecosystemGeison Goes
 
JCR - Java Content Repositories
JCR - Java Content RepositoriesJCR - Java Content Repositories
JCR - Java Content RepositoriesCarsten Ziegeler
 
Java, Ruby & Rails
Java, Ruby & RailsJava, Ruby & Rails
Java, Ruby & RailsPeter Lind
 
DataMapper on Infinispan
DataMapper on InfinispanDataMapper on Infinispan
DataMapper on InfinispanLance Ball
 
Ruby on Rails All Hands Meeting
Ruby on Rails All Hands MeetingRuby on Rails All Hands Meeting
Ruby on Rails All Hands MeetingDan Davis
 
Middleware as Code with mruby
Middleware as Code with mrubyMiddleware as Code with mruby
Middleware as Code with mrubyHiroshi SHIBATA
 
Introduction to Ruby on Rails
Introduction to Ruby on RailsIntroduction to Ruby on Rails
Introduction to Ruby on RailsAmit Patel
 

What's hot (20)

Migrating PriceChirp to Rails 3.0: The Pain Points
Migrating PriceChirp to Rails 3.0: The Pain PointsMigrating PriceChirp to Rails 3.0: The Pain Points
Migrating PriceChirp to Rails 3.0: The Pain Points
 
Ruby on Rails Presentation
Ruby on Rails PresentationRuby on Rails Presentation
Ruby on Rails Presentation
 
RoR (Ruby on Rails)
RoR (Ruby on Rails)RoR (Ruby on Rails)
RoR (Ruby on Rails)
 
Ruby On Rails
Ruby On RailsRuby On Rails
Ruby On Rails
 
Introduction to Rails - presented by Arman Ortega
Introduction to Rails - presented by Arman OrtegaIntroduction to Rails - presented by Arman Ortega
Introduction to Rails - presented by Arman Ortega
 
How DSL works on Ruby
How DSL works on RubyHow DSL works on Ruby
How DSL works on Ruby
 
Java presentation
Java presentationJava presentation
Java presentation
 
Ruby on Rails survival guide of an aged Java developer
Ruby on Rails survival guide of an aged Java developerRuby on Rails survival guide of an aged Java developer
Ruby on Rails survival guide of an aged Java developer
 
Ruby - a tester's best friend
Ruby - a tester's best friendRuby - a tester's best friend
Ruby - a tester's best friend
 
Buildr In Action @devoxx france 2012
Buildr In Action @devoxx france 2012Buildr In Action @devoxx france 2012
Buildr In Action @devoxx france 2012
 
PECL Picks - Extensions to make your life better
PECL Picks - Extensions to make your life betterPECL Picks - Extensions to make your life better
PECL Picks - Extensions to make your life better
 
An introduction to the ruby ecosystem
An introduction to the ruby ecosystemAn introduction to the ruby ecosystem
An introduction to the ruby ecosystem
 
JCR - Java Content Repositories
JCR - Java Content RepositoriesJCR - Java Content Repositories
JCR - Java Content Repositories
 
Java, Ruby & Rails
Java, Ruby & RailsJava, Ruby & Rails
Java, Ruby & Rails
 
DataMapper on Infinispan
DataMapper on InfinispanDataMapper on Infinispan
DataMapper on Infinispan
 
Workin On The Rails Road
Workin On The Rails RoadWorkin On The Rails Road
Workin On The Rails Road
 
Till Vollmer Presentation
Till Vollmer PresentationTill Vollmer Presentation
Till Vollmer Presentation
 
Ruby on Rails All Hands Meeting
Ruby on Rails All Hands MeetingRuby on Rails All Hands Meeting
Ruby on Rails All Hands Meeting
 
Middleware as Code with mruby
Middleware as Code with mrubyMiddleware as Code with mruby
Middleware as Code with mruby
 
Introduction to Ruby on Rails
Introduction to Ruby on RailsIntroduction to Ruby on Rails
Introduction to Ruby on Rails
 

Viewers also liked

Rails 3 generators
Rails 3 generatorsRails 3 generators
Rails 3 generatorsjoshsmoore
 
Rails Text Mate Cheats
Rails Text Mate CheatsRails Text Mate Cheats
Rails Text Mate Cheatsdezarrolla
 
Ruby on Rails Kickstart 103 & 104
Ruby on Rails Kickstart 103 & 104Ruby on Rails Kickstart 103 & 104
Ruby on Rails Kickstart 103 & 104Heng-Yi Wu
 
Railsguide
RailsguideRailsguide
Railsguidelanlau
 
Rails 3 Beginner to Builder 2011 Week 3
Rails 3 Beginner to Builder 2011 Week 3Rails 3 Beginner to Builder 2011 Week 3
Rails 3 Beginner to Builder 2011 Week 3Richard Schneeman
 
Introducing Command Line Applications with Ruby
Introducing Command Line Applications with RubyIntroducing Command Line Applications with Ruby
Introducing Command Line Applications with RubyNikhil Mungel
 

Viewers also liked (10)

Rails 3 generators
Rails 3 generatorsRails 3 generators
Rails 3 generators
 
Ruby on Rails 101
Ruby on Rails 101Ruby on Rails 101
Ruby on Rails 101
 
Rails01
Rails01Rails01
Rails01
 
Rails Text Mate Cheats
Rails Text Mate CheatsRails Text Mate Cheats
Rails Text Mate Cheats
 
Rest and Rails
Rest and RailsRest and Rails
Rest and Rails
 
Ruby on Rails Kickstart 103 & 104
Ruby on Rails Kickstart 103 & 104Ruby on Rails Kickstart 103 & 104
Ruby on Rails Kickstart 103 & 104
 
Railsguide
RailsguideRailsguide
Railsguide
 
Rails 3 Beginner to Builder 2011 Week 3
Rails 3 Beginner to Builder 2011 Week 3Rails 3 Beginner to Builder 2011 Week 3
Rails 3 Beginner to Builder 2011 Week 3
 
Introducing Command Line Applications with Ruby
Introducing Command Line Applications with RubyIntroducing Command Line Applications with Ruby
Introducing Command Line Applications with Ruby
 
Ruby on Rails for beginners
Ruby on Rails for beginnersRuby on Rails for beginners
Ruby on Rails for beginners
 

Similar to Intro to Ruby and Rails: Dynamic Languages, MVC, and More

Similar to Intro to Ruby and Rails: Dynamic Languages, MVC, and More (20)

Introduction to Ruby
Introduction to RubyIntroduction to Ruby
Introduction to Ruby
 
Ruby Metaprogramming 08
Ruby Metaprogramming 08Ruby Metaprogramming 08
Ruby Metaprogramming 08
 
Workin ontherailsroad
Workin ontherailsroadWorkin ontherailsroad
Workin ontherailsroad
 
WorkinOnTheRailsRoad
WorkinOnTheRailsRoadWorkinOnTheRailsRoad
WorkinOnTheRailsRoad
 
Ruby On Rails Introduction
Ruby On Rails IntroductionRuby On Rails Introduction
Ruby On Rails Introduction
 
Bhavesh ro r
Bhavesh ro rBhavesh ro r
Bhavesh ro r
 
Ruby on rails
Ruby on railsRuby on rails
Ruby on rails
 
Ruby on rails
Ruby on railsRuby on rails
Ruby on rails
 
Ruby on rails
Ruby on railsRuby on rails
Ruby on rails
 
Ruby on Rails
Ruby on Rails Ruby on Rails
Ruby on Rails
 
Why Ruby?
Why Ruby? Why Ruby?
Why Ruby?
 
Ruby
RubyRuby
Ruby
 
Ruby on Rails Presentation
Ruby on Rails PresentationRuby on Rails Presentation
Ruby on Rails Presentation
 
Ruby on Rails (RoR) as a back-end processor for Apex
Ruby on Rails (RoR) as a back-end processor for Apex Ruby on Rails (RoR) as a back-end processor for Apex
Ruby on Rails (RoR) as a back-end processor for Apex
 
Ruby on rails for beginers
Ruby on rails for beginersRuby on rails for beginers
Ruby on rails for beginers
 
Rubyonrails 120409061835-phpapp02
Rubyonrails 120409061835-phpapp02Rubyonrails 120409061835-phpapp02
Rubyonrails 120409061835-phpapp02
 
Ruby on Rails Introduction M&P - IT Skill Development Program 07
Ruby on Rails Introduction M&P - IT Skill Development Program 07Ruby on Rails Introduction M&P - IT Skill Development Program 07
Ruby on Rails Introduction M&P - IT Skill Development Program 07
 
Ruby on Rails - An overview
Ruby on Rails -  An overviewRuby on Rails -  An overview
Ruby on Rails - An overview
 
The Joy Of Ruby
The Joy Of RubyThe Joy Of Ruby
The Joy Of Ruby
 
Ruby on Rails 3 Day BC
Ruby on Rails 3 Day BCRuby on Rails 3 Day BC
Ruby on Rails 3 Day BC
 

More from Mark Menard

Let's Do Some Upfront Design - WindyCityRails 2014
Let's Do Some Upfront Design - WindyCityRails 2014Let's Do Some Upfront Design - WindyCityRails 2014
Let's Do Some Upfront Design - WindyCityRails 2014Mark Menard
 
A Tour of Wyriki
A Tour of WyrikiA Tour of Wyriki
A Tour of WyrikiMark Menard
 
Small Code - RailsConf 2014
Small Code - RailsConf 2014Small Code - RailsConf 2014
Small Code - RailsConf 2014Mark Menard
 
Small Code - Ruby on Ales 2014
Small Code - Ruby on Ales 2014Small Code - Ruby on Ales 2014
Small Code - Ruby on Ales 2014Mark Menard
 
Write Small Things (Code)
Write Small Things (Code)Write Small Things (Code)
Write Small Things (Code)Mark Menard
 
JRuby 6 Years in Production
JRuby 6 Years in ProductionJRuby 6 Years in Production
JRuby 6 Years in ProductionMark Menard
 
Conference of Grand Masters Tech Talk 2013
Conference of Grand Masters Tech Talk 2013Conference of Grand Masters Tech Talk 2013
Conference of Grand Masters Tech Talk 2013Mark Menard
 
Startup Lessons Learned
Startup Lessons LearnedStartup Lessons Learned
Startup Lessons LearnedMark Menard
 
Mobile Platforms and App Development
Mobile Platforms and App DevelopmentMobile Platforms and App Development
Mobile Platforms and App DevelopmentMark Menard
 
Ruby on Rails Training - Module 2
Ruby on Rails Training - Module 2Ruby on Rails Training - Module 2
Ruby on Rails Training - Module 2Mark Menard
 
Intro to Rails ActiveRecord
Intro to Rails ActiveRecordIntro to Rails ActiveRecord
Intro to Rails ActiveRecordMark Menard
 
Behavior Driven Development with Rails
Behavior Driven Development with RailsBehavior Driven Development with Rails
Behavior Driven Development with RailsMark Menard
 
Intro to Ruby on Rails
Intro to Ruby on RailsIntro to Ruby on Rails
Intro to Ruby on RailsMark Menard
 
JRuby in a Java World
JRuby in a Java WorldJRuby in a Java World
JRuby in a Java WorldMark Menard
 

More from Mark Menard (14)

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

Recently uploaded

A Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersA Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersNicole Novielli
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteDianaGray10
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...Rick Flair
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxLoriGlavin3
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxLoriGlavin3
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionDilum Bandara
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxLoriGlavin3
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsPixlogix Infotech
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenHervé Boutemy
 
What is Artificial Intelligence?????????
What is Artificial Intelligence?????????What is Artificial Intelligence?????????
What is Artificial Intelligence?????????blackmambaettijean
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .Alan Dix
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxLoriGlavin3
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESSALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESmohitsingh558521
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity PlanDatabarracks
 

Recently uploaded (20)

A Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersA Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software Developers
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test Suite
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An Introduction
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and Cons
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache Maven
 
What is Artificial Intelligence?????????
What is Artificial Intelligence?????????What is Artificial Intelligence?????????
What is Artificial Intelligence?????????
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptx
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESSALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity Plan
 

Intro to Ruby and Rails: Dynamic Languages, MVC, and More

  • 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

  1. \n
  2. \n
  3. \n
  4. \n
  5. \n
  6. \n
  7. \n
  8. \n
  9. \n
  10. \n
  11. \n
  12. \n
  13. \n
  14. \n
  15. \n
  16. \n
  17. \n
  18. \n
  19. \n
  20. \n
  21. \n
  22. \n
  23. \n
  24. \n
  25. \n
  26. \n
  27. \n
  28. \n
  29. \n
  30. \n
  31. \n
  32. \n
  33. \n
  34. \n
  35. \n
  36. \n
  37. \n
  38. \n
  39. \n
  40. \n
  41. \n
  42. \n
  43. \n
  44. \n
  45. \n
  46. \n
  47. \n
  48. \n
  49. \n
  50. \n
  51. \n
  52. \n
  53. \n
  54. \n
  55. \n
  56. \n
  57. \n
  58. \n
  59. \n
  60. \n
  61. \n
  62. \n
  63. \n
  64. \n
  65. \n
  66. \n
  67. \n