KEMBAR78
Intro to Ruby on Rails | PPT
Intro to Ruby on Rails by Mark Menard Vita Rara, Inc.
Ruby © Vita Rara, Inc. “ 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”
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   © Vita Rara, Inc.
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. © Vita Rara, Inc.
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 Integrated Ajax support © Vita Rara, Inc.
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 © Vita Rara, Inc.
Rake: The Ruby Make Rake lets you define a dependency tree of tasks to be executed. Rake tasks are loaded from the file Rakefile Rake automates and simplifies creating and managing the development of a Rails project. © Vita Rara, Inc.
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. © Vita Rara, Inc.
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. © Vita Rara, Inc.
Migrations Typical migration functions: create_table add_column change_column rename_column rename_table add_index © Vita Rara, Inc.
Migration Example © Vita Rara, Inc. create_table  "users" , :force => true  do  |t|  t.string :login, :email, :remember_token  t.string :salt, :crypted_password, :limit =>  40   t.timestamps  t.datetime :remember_token_expires_at  end
ActiveRecord 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   © Vita Rara, Inc.
ActiveRecord Model Example © Vita Rara, Inc. create_table  &quot;persons&quot;   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
CRUD Create: create, new Read: find, find_by_<attribute> Update: save, update_attributes Delete: destroy © Vita Rara, Inc.
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]) © Vita Rara, Inc.
Advanced Finding Finders also support: :limit :offset :order :joins :select :group © Vita Rara, Inc.
Update user = User.find(1) user.first_name = ‘Mark’ user.last_name = ‘Menard’ user.save! © Vita Rara, Inc.
Transactions Account.transaction do account1.deposit(100) account2.withdraw(100) end © Vita Rara, Inc.
ActiveRecord Associations Joining Things Together
ActiveRecord Associations Two primary types of associations: belongs_to has_one / has_many There are others, but they are not commonly used. © Vita Rara, Inc.
ActiveRecord Associations © Vita Rara, Inc. # 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
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() © Vita Rara, Inc.
ActiveRecord Validations Keeping Your Data Safe
Validation 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  © Vita Rara, Inc.
Validation Callback Methods validate validate_on_create validate_on_update © Vita Rara, Inc.
Validation Example © Vita Rara, Inc. 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
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  © Vita Rara, Inc.
Validation Macro Example © Vita Rara, Inc. 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
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  © Vita Rara, Inc.
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  © Vita Rara, Inc.
A Simple Controller © Vita Rara, Inc. 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 =>  &quot;new&quot; end end ... end
Sessions A hash stored on the server, typically in a database table or in 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]   © Vita Rara, Inc.
ActionView Our Face to the World
What is 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.  © Vita Rara, Inc.
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’ © Vita Rara, Inc.
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.   © Vita Rara, Inc.
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. © Vita Rara, Inc.
Example View © Vita Rara, Inc. <p> <b>Name:</b> <%=h @category.name %> </p> <%= link_to  'Edit' , edit_category_path(@category) %> | <%= link_to  'Back' , categories_path %>
A Check Book Ledger Example
Basic Requirements The System should allow the management of multiple accounts The system should maintain an account ledger for every account in the system. Each account ledger should consist of ledger entries. Each ledger entry can be either a positive or negative value. Ledger entries can be associated with a payee and a category. © Vita Rara, Inc.
Implementing a Check Book Ledger Create a new project Theme the project Define our resources using:  script/generate scaffold Account Ledger Entry Payee Category Theme models Implement  © Vita Rara, Inc.
Shameless Self Promotion
Ruby and Rail 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 © Vita Rara, Inc.
Ruby on Rails Consulting Full Life Cycle Project Development Inception Implementation Deployment Long Term Support Ruby on Rails Mentoring Get your team up to speed using Rails © Vita Rara, Inc.
Contact Information Mark Menard [email_address] http://www.vitarara.net / 518 369 7356 © Vita Rara, Inc.

Intro to Ruby on Rails

  • 1.
    Intro to Rubyon Rails by Mark Menard Vita Rara, Inc.
  • 2.
    Ruby © VitaRara, Inc. “ 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”
  • 3.
    Ruby on RailsRuby 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 © Vita Rara, Inc.
  • 4.
    The Elevator PitchRuby 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. © Vita Rara, Inc.
  • 5.
    Overview Rails isa 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 Integrated Ajax support © Vita Rara, Inc.
  • 6.
    The Rails PhilosophyRuby - 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 © Vita Rara, Inc.
  • 7.
    Rake: The RubyMake Rake lets you define a dependency tree of tasks to be executed. Rake tasks are loaded from the file Rakefile Rake automates and simplifies creating and managing the development of a Rails project. © Vita Rara, Inc.
  • 8.
    Environments Rails hassupport for multiple execution environments. Environments encapsulate database settings and other configuration. Typical environments Development Test Production Additional environments are easy to add. © Vita Rara, Inc.
  • 9.
  • 10.
    Managing Data SchemasRails 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. © Vita Rara, Inc.
  • 11.
    Migrations Typical migrationfunctions: create_table add_column change_column rename_column rename_table add_index © Vita Rara, Inc.
  • 12.
    Migration Example ©Vita Rara, Inc. create_table &quot;users&quot; , :force => true do |t| t.string :login, :email, :remember_token t.string :salt, :crypted_password, :limit => 40 t.timestamps t.datetime :remember_token_expires_at end
  • 13.
  • 14.
    Fundamentals One databasetable 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 © Vita Rara, Inc.
  • 15.
    ActiveRecord Model Example© Vita Rara, Inc. create_table &quot;persons&quot; 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
  • 16.
    CRUD Create: create,new Read: find, find_by_<attribute> Update: save, update_attributes Delete: destroy © Vita Rara, Inc.
  • 17.
    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]) © Vita Rara, Inc.
  • 18.
    Advanced Finding Findersalso support: :limit :offset :order :joins :select :group © Vita Rara, Inc.
  • 19.
    Update user =User.find(1) user.first_name = ‘Mark’ user.last_name = ‘Menard’ user.save! © Vita Rara, Inc.
  • 20.
    Transactions Account.transaction doaccount1.deposit(100) account2.withdraw(100) end © Vita Rara, Inc.
  • 21.
  • 22.
    ActiveRecord Associations Twoprimary types of associations: belongs_to has_one / has_many There are others, but they are not commonly used. © Vita Rara, Inc.
  • 23.
    ActiveRecord Associations ©Vita Rara, Inc. # 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
  • 24.
    Association Methods Associationsadd 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() © Vita Rara, Inc.
  • 25.
  • 26.
    Validation Validations arerules 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 © Vita Rara, Inc.
  • 27.
    Validation Callback Methodsvalidate validate_on_create validate_on_update © Vita Rara, Inc.
  • 28.
    Validation Example ©Vita Rara, Inc. 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
  • 29.
    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 © Vita Rara, Inc.
  • 30.
    Validation Macro Example© Vita Rara, Inc. 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
  • 31.
  • 32.
    Controllers Controllers areRuby classes that live under app/ controllers Controller classes extend ActionController::Base An action is a public method and/or a corresponding view template © Vita Rara, Inc.
  • 33.
    Rendering a ResponseA 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 © Vita Rara, Inc.
  • 34.
    A Simple Controller© Vita Rara, Inc. 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 => &quot;new&quot; end end ... end
  • 35.
    Sessions A hashstored on the server, typically in a database table or in 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] © Vita Rara, Inc.
  • 36.
    ActionView Our Faceto the World
  • 37.
    What is 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. © Vita Rara, Inc.
  • 38.
    Where do templateslive? 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’ © Vita Rara, Inc.
  • 39.
    Template Environment Templateshave 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. © Vita Rara, Inc.
  • 40.
    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. © Vita Rara, Inc.
  • 41.
    Example View ©Vita Rara, Inc. <p> <b>Name:</b> <%=h @category.name %> </p> <%= link_to 'Edit' , edit_category_path(@category) %> | <%= link_to 'Back' , categories_path %>
  • 42.
    A Check BookLedger Example
  • 43.
    Basic Requirements TheSystem should allow the management of multiple accounts The system should maintain an account ledger for every account in the system. Each account ledger should consist of ledger entries. Each ledger entry can be either a positive or negative value. Ledger entries can be associated with a payee and a category. © Vita Rara, Inc.
  • 44.
    Implementing a CheckBook Ledger Create a new project Theme the project Define our resources using: script/generate scaffold Account Ledger Entry Payee Category Theme models Implement © Vita Rara, Inc.
  • 45.
  • 46.
    Ruby and RailTraining 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 © Vita Rara, Inc.
  • 47.
    Ruby on RailsConsulting Full Life Cycle Project Development Inception Implementation Deployment Long Term Support Ruby on Rails Mentoring Get your team up to speed using Rails © Vita Rara, Inc.
  • 48.
    Contact Information MarkMenard [email_address] http://www.vitarara.net / 518 369 7356 © Vita Rara, Inc.