Ruby On Rails Gautam Rege Josh Software Pvt. Ltd.
Speaker Introduction <ul><li>9 years Software Experience </li></ul><ul><li>BE – PICT </li></ul><ul><li>Working in rails si...
Part – 1  Ruby on Rails Introduction
History of Ruby <ul><li>Father of Ruby –  Yukihiro Matsumoto, a.k.a. “Matz”, Japan, 1995 </li></ul><ul><li>Ruby is an Obje...
Ruby Vs Python <ul><li>Python  was the first OO script but its not a pure OO. There is no real encapsulation. </li></ul><u...
Ruby Vs Perl <ul><li>Perl is really a procedural language.  </li></ul><ul><li>OO Perl was introduced later. </li></ul><ul>...
Ruby Vs Perl contd.. <ul><li>foreach $item(@fields) {    if ($db{$item}) {    print &quot;conflict on $item
&quot;;    $er...
Features of Ruby <ul><li>Pure Object Oriented Script </li></ul><ul><li>No indentation issues. </li></ul><ul><li>Readable c...
What do I choose anyway?? <ul><li>Perl is for people who believe that ‘old is gold’ and are set in their ways.  </li></ul>...
Overall Comparison Rails Pylons cgi/perl Web-frameworks    Plug-ins / auto-installation    Object Oriented Nature  ...
Web Technologies <ul><li>Java – J2EE </li></ul><ul><li>Python – Pylons, CGI </li></ul><ul><li>PHP </li></ul><ul><li>Perl –...
J2EE, .NET Web Development <ul><li>J2EE. .NET are very evolved and very good for robust and heavy applications. </li></ul>...
CGI / Perl & PHP <ul><li>Simple architecture – so very fast </li></ul><ul><li>WordPress is a PHP (XML-RPC) site </li></ul>...
Pylons <ul><li>Pylons is the Python Web-framework </li></ul><ul><li>Follows MVC pattern </li></ul><ul><li>Relatively very ...
Ruby on Rails <ul><li>Pure MVC framework </li></ul><ul><ul><li>Model </li></ul></ul><ul><ul><li>View </li></ul></ul><ul><u...
Ruby On Rails contd.. <ul><li>Support simple multi-tier architecture </li></ul><ul><ul><li>Webserver </li></ul></ul><ul><u...
Rails in the Real World <ul><li>Who uses Rails today? </li></ul><ul><li>Twitter, Facebook Applications </li></ul><ul><li>V...
Part 2 – Rails Architecture
Terminologies <ul><li>MVC </li></ul><ul><ul><li>Model - View – Controller Design Pattern </li></ul></ul><ul><li>REST </li>...
Model – View – Controller
Model - Overview <ul><li>Maintains state of an object / application. </li></ul><ul><li>Manages the actual data involved. <...
Controller – Overview <ul><li>Control the logical flow of the request. </li></ul><ul><li>Interact with model and render th...
View – Overview <ul><li>Views are HTML renderers </li></ul><ul><li>Render dynamic pages based on templates. </li></ul><ul>...
MVC in Rails
Routing in Rails <ul><li>http://host:port/:controller/:action/:id </li></ul><ul><li>They determine </li></ul><ul><ul><li>W...
A word about RESTfull Rails Routes: map.resources :teams
Session Break Coffee ?
Part 2.1 ActiveRecord <ul><li>Database Connectors </li></ul><ul><ul><li>Mysql, pgsql, sqlite </li></ul></ul><ul><li>ORM </...
Object Relational Mapping <ul><li>Database </li></ul><ul><ul><li>create table `customers` ( </li></ul></ul><ul><ul><li>`id...
Database “rules” <ul><li>Rules would mean guidelines. They help in writing lesser code and allow easier access from Rails ...
Database “rules” contd.. <ul><li>All datetime fields should have `_at` suffix. Example: `created_at` </li></ul><ul><li>Avo...
Part 2.4 Migrations <ul><li>Migrations are routines which help us manage the database. </li></ul><ul><li>Versions are main...
Example of Migration <ul><li>class CreateAddresses < ActiveRecord::Migration </li></ul><ul><ul><li>def self.up </li></ul><...
Rake <ul><li>Ruby build program similar to ‘make’ </li></ul><ul><li>Rakefiles (rake‘s version of Makefiles) are completely...
Part 3 – Hands-on work Building a Rails Application
Ruby on Rails Installation <ul><li>Install ruby on Windows / Linux. </li></ul><ul><ul><li>Latest stable version: Ruby 1.8....
Setup the Environment <ul><li>Ensure installation is good and versions are correct. </li></ul><ul><ul><li>ruby –v >= 1.8.6...
Rails Project Layout ..../app  ......../controller  ......../helpers  ......../models  ......../views  ............/layout...
Session Break Coffee ?
ActiveRecord Validations <ul><li>validate </li></ul><ul><ul><li>Generic validation method that can be used for custom vali...
ActiveRecord Callbacks <ul><li>before_create </li></ul><ul><li>after_create </li></ul><ul><li>before_save </li></ul><ul><l...
ActiveRecord Relations <ul><li>has_many </li></ul><ul><ul><li>1  ↔  m relationship with child </li></ul></ul><ul><li>belon...
Database revisit <ul><ul><li>create table `customers` ( </li></ul></ul><ul><ul><ul><li>`id` int(11) auto_increment,  </li>...
has_one  ↔  belongs_to <ul><li>class Customer < ActiveRecord::Base </li></ul><ul><li>has_one :address </li></ul><ul><li>en...
Database revisit <ul><ul><li>create table `bank_accounts` ( </li></ul></ul><ul><ul><ul><li>`id` int(11) auto_increment,  <...
has_many  ↔  belongs_to <ul><li>class Customer < ActiveRecord::Base </li></ul><ul><li>has_many :bank_accounts </li></ul><u...
Database Revist <ul><ul><li>create table `products` ( </li></ul></ul><ul><ul><ul><li>`id` int(11) auto_increment,  </li></...
has_many :through => <ul><li>class Customer < ActiveRecord::Base </li></ul><ul><li>has_many :bank_account_customers </li><...
Named Scopes <ul><li>ActiveRecord::NamedScope::Scope </li></ul><ul><li>A scope represents a narrowing of a database query ...
Named Scope example class Customer < ActiveRecord::Base has_many :bank_accounts named_scope :hni, :conditions => [ ‘hni = ...
Hands On! <ul><li>Creating & updating migrations </li></ul><ul><ul><li>Adding relationships </li></ul></ul><ul><li>Rails c...
Session Break Coffee ?
Part 2.2 ActionController <ul><li>Rails HTTP request processing </li></ul><ul><li>Helpers </li></ul><ul><li>Filters </li><...
Processing a HTTP Rails request <ul><li>http:// host:port /:controller/:action/:id </li></ul><ul><ul><li>http://some.url:3...
Helpers <ul><li>Helpers are not classes but modules. </li></ul><ul><li>They mainly assist views with some helper functions...
Filters <ul><li>before_filter, after_filter are controller class methods  </li></ul><ul><li>Filters can be used to check a...
ActionController example <ul><li>app/controllers/customer_controller.rb: </li></ul><ul><li>class CustomerController < Appl...
Part 2.3 ActionView <ul><li>Embedded Ruby (erb) </li></ul><ul><li>Rails Magic </li></ul><ul><ul><li>Instance variables (@v...
Partials <ul><li>Partials are views which can be rendered in other views. </li></ul><ul><li>They are always stored with a ...
Layouts <ul><li>The basic page layout for all pages. </li></ul><ul><li>Default layout: application.erb.html </li></ul><ul>...
Rendering Views <ul><li>Embedded Ruby code without rendering </li></ul><ul><ul><li><% %> </li></ul></ul><ul><li>Rendering ...
FormHelpers <ul><li><% form_for :customer @customer :url =>  {:action => :create} do |f| %> </li></ul><ul><ul><li><%= f.te...
Ajax on Rails <ul><li>Link_to_remote </li></ul><ul><li>Remote_form_for </li></ul><ul><li>Rails supports different renderin...
Session Break Coffee ?
Building a Rails Application <ul><li>Installing Ruby, rubygems and Rails </li></ul><ul><li>Rails Project Layout </li></ul>...
Application Idea?? Lets think of one now Pre-decided
Survey Application <ul><li>A survey is a set of questions which a user answers </li></ul><ul><li>Application should have m...
Survey Application <ul><li>Result of the survey for a user should be shown. </li></ul><ul><li>User can edit his previous a...
Is the above too easy ??   <ul><li>Questions can be free-text or multiple choice. </li></ul><ul><li>User authorization </...
Survey Application survey questions answers users
Relationships <ul><li>A survey has_many questions </li></ul><ul><li>A question has_many answers </li></ul><ul><li>A user h...
Migrations <ul><li>Survey Migration </li></ul><ul><ul><li>t.string :name </li></ul></ul><ul><li>User Migration </li></ul><...
Migrations contd.. <ul><li>Questions Migration </li></ul><ul><ul><li>T.string value </li></ul></ul><ul><ul><li>T.reference...
Scaffolding <ul><li>Generate scaffolds </li></ul><ul><li>./script/generate scaffold Customer </li></ul><ul><ul><li>This ge...
Checklist <ul><li>Migrations completed? </li></ul><ul><li>Model relationships added? </li></ul><ul><li>Config/database.yml...
Actual Development (finally) <ul><li>Add code to controller </li></ul><ul><li>Add validation to models </li></ul><ul><li>M...
Session Break Coffee ?
Deploying the application <ul><li>Starting rails server </li></ul><ul><ul><li>RAILS_ROOT/script/start </li></ul></ul><ul><...
Configuring routes <ul><li>Resource Maps </li></ul><ul><ul><li>map.resources :customer  => Customer route </li></ul></ul><...
Enterprise Deployment <ul><li>Nginx + mongrel </li></ul><ul><li>Nginx + thin </li></ul><ul><li>Apache + Passenger </li></u...
Capistrano – Rails Deployment <ul><li>Capify </li></ul><ul><li>config/deploy.rb </li></ul><ul><li>cap –T deploy </li></ul>...
Session Break Coffee ?
Advanced Topics <ul><li>Behavior Driven Development </li></ul><ul><li>Test Driven Development </li></ul><ul><li>Rspec </li...
Behaviour Driven Development <ul><li>Standard SDLC process defines this. </li></ul><ul><li>Testing is done after developme...
Test Driven Development <ul><li>Part of Agile </li></ul><ul><li>Testing and Development go on in parallel  </li></ul><ul><...
Rspec  <ul><li>Rspec for Models, Controllers and Views </li></ul><ul><li>Books for Rspec are still being written ! </li></...
Nuances of Rspec <ul><li>Describe => the context or object  </li></ul><ul><li>It => test case </li></ul><ul><li>Before and...
Rspec - Typical Example <ul><ul><li>describe &quot;A new Account&quot; do </li></ul></ul><ul><ul><li>it &quot;should have ...
Rspec – Pending Examples <ul><li>Describe “Customer” do </li></ul><ul><ul><li>It “should have a address” </li></ul></ul><u...
Before & After Code  <ul><li>Before(:each) </li></ul><ul><ul><li>Before each it() executes </li></ul></ul><ul><li>Before(:...
Before & after code example <ul><li>Describe Account do </li></ul><ul><ul><li>before(:each) </li></ul></ul><ul><ul><ul><li...
Helper Routines <ul><li>Describe Customer, “when risky” do </li></ul><ul><ul><li>def get_terror_list </li></ul></ul><ul><u...
Rspec – further reading <ul><li>Shared Examples </li></ul><ul><li>Nested Examples </li></ul><ul><li>Spec::Mock objects </l...
Hands On! <ul><li>rails proj1 -d mysql </li></ul><ul><li>cd proj1/ </li></ul><ul><li>./script/generate rspec </li></ul><ul...
References <ul><li>Books </li></ul><ul><ul><li>Rails Recipes – Chad Fowler  </li></ul></ul><ul><ul><ul><li>http://www.prag...
Thank You!
Upcoming SlideShare
Loading in...5
×

Ruby On Rails

5,145

Published on

Ruby On Rails basics

0 Comments
1 Like
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total Views
5,145
On Slideshare
0
From Embeds
0
Number of Embeds
1
Actions
Shares
0
Downloads
0
Comments
0
Likes
1
Embeds 0
No embeds

No notes for slide

Ruby On Rails

  1. 1. Ruby On Rails Gautam Rege Josh Software Pvt. Ltd.
  2. 2. Speaker Introduction <ul><li>9 years Software Experience </li></ul><ul><li>BE – PICT </li></ul><ul><li>Working in rails since 2006 </li></ul><ul><li>Co-founded Josh Software – 2007 </li></ul><ul><li>Previous Experience </li></ul><ul><ul><li>Cybage, Zensar, Symantec </li></ul></ul>
  3. 3. Part – 1 Ruby on Rails Introduction
  4. 4. History of Ruby <ul><li>Father of Ruby – Yukihiro Matsumoto, a.k.a. “Matz”, Japan, 1995 </li></ul><ul><li>Ruby is an Object Oriented Scripting Language </li></ul><ul><li>Object Oriented helps in designing applications </li></ul><ul><li>Scripting makes it faster and quicker to develop and redeploy. </li></ul>
  5. 5. Ruby Vs Python <ul><li>Python was the first OO script but its not a pure OO. There is no real encapsulation. </li></ul><ul><li>Indentation !! </li></ul><ul><ul><li>def foo: </li></ul></ul><ul><ul><li>print “This is the first line” </li></ul></ul><ul><ul><li>print “This is second line” </li></ul></ul><ul><ul><li>print “This is a syntax error” </li></ul></ul><ul><li>Serious Ruby Competitor </li></ul><ul><li>Lots of python plugins and auto-install features </li></ul><ul><li>Very popular today </li></ul><ul><li>Caveats: </li></ul><ul><ul><li>Python – Why the name? </li></ul></ul>
  6. 6. Ruby Vs Perl <ul><li>Perl is really a procedural language. </li></ul><ul><li>OO Perl was introduced later. </li></ul><ul><li>Syntax difficult to understand: $ @ % </li></ul><ul><li>Excellent stream parser.. That was the original purpose. </li></ul><ul><li>Caveats: </li></ul><ul><ul><li>Perl - Practical Extraction and Report Language </li></ul></ul>
  7. 7. Ruby Vs Perl contd.. <ul><li>foreach $item(@fields) {   if ($db{$item}) {   print &quot;conflict on $item &quot;;   $err ++;   next;   }  $db{$item} = @fields;  } </li></ul><ul><li>fields.each { |item| </li></ul><ul><ul><li>puts “conflict on #{item}” if fields.include?(item) } </li></ul></ul>
  8. 8. Features of Ruby <ul><li>Pure Object Oriented Script </li></ul><ul><li>No indentation issues. </li></ul><ul><li>Readable code. </li></ul><ul><li>Blocks and Iterators </li></ul><ul><li>Instance and Class variables </li></ul><ul><li>Caveats: </li></ul><ul><ul><li>What is the difference between, Proc, Lamda, a normal function </li></ul></ul>
  9. 9. What do I choose anyway?? <ul><li>Perl is for people who believe that ‘old is gold’ and are set in their ways. </li></ul><ul><li>Python is for ‘veterans’: people more comfortable on unix and vi than on Windows and Word! </li></ul><ul><li>Ruby is for ‘enthusiasts’. You treat Ruby like you ‘pet’. You code because you enjoy it, watch it grow AND groom it as you like. </li></ul>
  10. 10. Overall Comparison Rails Pylons cgi/perl Web-frameworks    Plug-ins / auto-installation    Object Oriented Nature  Weak References (leaks)    Garbage Collection    Loose Data Typing    Data Types: Arrays, Hash Ruby Python Perl Features
  11. 11. Web Technologies <ul><li>Java – J2EE </li></ul><ul><li>Python – Pylons, CGI </li></ul><ul><li>PHP </li></ul><ul><li>Perl – CGI </li></ul><ul><li>Ruby – Rails </li></ul><ul><li>.NET – ASP, C# </li></ul>
  12. 12. J2EE, .NET Web Development <ul><li>J2EE. .NET are very evolved and very good for robust and heavy applications. </li></ul><ul><li>They support different levels of tier architecture – EJB, databases </li></ul><ul><li>Excellent Security – application and code </li></ul><ul><li>Excellent Load Balancing and clustering support </li></ul><ul><li>Deployment is complicated </li></ul><ul><li>Development is slow </li></ul><ul><li>Very expensive for commercial deployment </li></ul>
  13. 13. CGI / Perl & PHP <ul><li>Simple architecture – so very fast </li></ul><ul><li>WordPress is a PHP (XML-RPC) site </li></ul><ul><li>Facebook </li></ul><ul><li>Very difficult to support multi-tier architecture </li></ul><ul><li>Security is weak </li></ul><ul><li>Poor clustering support </li></ul><ul><li>SQL centric code </li></ul><ul><li>Typically procedural in nature </li></ul><ul><ul><li>Not suited for complicated web applications </li></ul></ul><ul><ul><li>Very good for simple websites with small dynamic content </li></ul></ul>
  14. 14. Pylons <ul><li>Pylons is the Python Web-framework </li></ul><ul><li>Follows MVC pattern </li></ul><ul><li>Relatively very new. </li></ul><ul><li>Based on Rails architecture </li></ul>
  15. 15. Ruby on Rails <ul><li>Pure MVC framework </li></ul><ul><ul><li>Model </li></ul></ul><ul><ul><li>View </li></ul></ul><ul><ul><li>Controller </li></ul></ul><ul><li>Evolved over the past 4 years </li></ul><ul><li>Authentication / Authorization very strong </li></ul><ul><li>Being slowly adopted for heavy web applications </li></ul>
  16. 16. Ruby On Rails contd.. <ul><li>Support simple multi-tier architecture </li></ul><ul><ul><li>Webserver </li></ul></ul><ul><ul><li>Database </li></ul></ul><ul><ul><li>Application Server </li></ul></ul><ul><li>Good clustering support with Nginx + thin, Apache + passenger </li></ul><ul><li>Security at code level is weak i.e. no source code encryption support yet. </li></ul>
  17. 17. Rails in the Real World <ul><li>Who uses Rails today? </li></ul><ul><li>Twitter, Facebook Applications </li></ul><ul><li>Vastly used as automated QA in large companies </li></ul><ul><li>One of the pioneers of Agile Methodology </li></ul><ul><li>JRuby – Java Ruby interpreter </li></ul>
  18. 18. Part 2 – Rails Architecture
  19. 19. Terminologies <ul><li>MVC </li></ul><ul><ul><li>Model - View – Controller Design Pattern </li></ul></ul><ul><li>REST </li></ul><ul><ul><li>Representational State Transfer </li></ul></ul><ul><li>ORM </li></ul><ul><ul><li>Object Relational Mapping </li></ul></ul><ul><li>Scaffold </li></ul><ul><ul><li>Building code skeletons. </li></ul></ul><ul><li>Migrations </li></ul><ul><ul><li>Managing the database tables and columns </li></ul></ul>
  20. 20. Model – View – Controller
  21. 21. Model - Overview <ul><li>Maintains state of an object / application. </li></ul><ul><li>Manages the actual data involved. </li></ul><ul><li>Validates object information </li></ul><ul><li>In Rails: </li></ul><ul><ul><li>It is directly mapped to the database table via ORM </li></ul></ul><ul><ul><li>It is independent of Database nuances. </li></ul></ul><ul><ul><li>Models supports relationships </li></ul></ul><ul><ul><li>Models have bulk of rails code </li></ul></ul><ul><ul><li>ActiveRecord </li></ul></ul>
  22. 22. Controller – Overview <ul><li>Control the logical flow of the request. </li></ul><ul><li>Interact with model and render the views </li></ul><ul><li>In Rails: </li></ul><ul><ul><li>Controllers manage authorization, sessions. </li></ul></ul><ul><ul><li>Controllers decide how the request is processed. </li></ul></ul><ul><ul><li>Render view according to business logic. </li></ul></ul><ul><ul><li>ActionController </li></ul></ul>
  23. 23. View – Overview <ul><li>Views are HTML renderers </li></ul><ul><li>Render dynamic pages based on templates. </li></ul><ul><ul><li>XML </li></ul></ul><ul><ul><li>Json </li></ul></ul><ul><ul><li>HTML </li></ul></ul><ul><ul><li>JS (Ajax) </li></ul></ul><ul><li>In Rails </li></ul><ul><ul><li>Should contain very less or NO logic </li></ul></ul><ul><ul><li>Erb (Embedded Ruby ) is supported. </li></ul></ul><ul><ul><li>ActionView </li></ul></ul>
  24. 24. MVC in Rails
  25. 25. Routing in Rails <ul><li>http://host:port/:controller/:action/:id </li></ul><ul><li>They determine </li></ul><ul><ul><li>Which controller </li></ul></ul><ul><ul><li>Which action </li></ul></ul><ul><ul><li>Which object </li></ul></ul><ul><li>Custom routes can also be setup. </li></ul>
  26. 26. A word about RESTfull Rails Routes: map.resources :teams
  27. 27. Session Break Coffee ?
  28. 28. Part 2.1 ActiveRecord <ul><li>Database Connectors </li></ul><ul><ul><li>Mysql, pgsql, sqlite </li></ul></ul><ul><li>ORM </li></ul><ul><li>Validations </li></ul><ul><li>Relationships </li></ul>
  29. 29. Object Relational Mapping <ul><li>Database </li></ul><ul><ul><li>create table `customers` ( </li></ul></ul><ul><ul><li>`id` int(11) auto_increment, </li></ul></ul><ul><ul><li>`name` varchar(64), </li></ul></ul><ul><ul><li>`age`int, </li></ul></ul><ul><ul><li>primary key `id`) </li></ul></ul><ul><li>Model </li></ul><ul><ul><li>class Customer < ActiveRecord::Base </li></ul></ul><ul><ul><li>end </li></ul></ul><ul><li>Object access </li></ul><ul><ul><li>cust = Customer.create </li></ul></ul><ul><ul><li>puts “#{cust.name}, #{cust.age}” </li></ul></ul>
  30. 30. Database “rules” <ul><li>Rules would mean guidelines. They help in writing lesser code and allow easier access from Rails code </li></ul><ul><li>All table names should be plural: </li></ul><ul><ul><li>customers, products, categories, people </li></ul></ul><ul><li>All tables should have `id` as primary key which is an auto_increment </li></ul><ul><li>All tables should have ‘_id` suffix as foreign keys. Example: `customer_id` in `products` table </li></ul>
  31. 31. Database “rules” contd.. <ul><li>All datetime fields should have `_at` suffix. Example: `created_at` </li></ul><ul><li>Avoid composite keys </li></ul><ul><ul><li>use model validations instead </li></ul></ul><ul><ul><li>They are new supported in Rails 2.1.2 onwards </li></ul></ul><ul><li>Model name should be singular. </li></ul><ul><ul><li>Model Customer maps to `customers` table </li></ul></ul><ul><ul><li>Model Category maps to `categories` table (!!) </li></ul></ul><ul><ul><li>Model Person maps to `people` table (!!) </li></ul></ul>
  32. 32. Part 2.4 Migrations <ul><li>Migrations are routines which help us manage the database. </li></ul><ul><li>Versions are maintained in the database itself in a table called schema_migrations </li></ul><ul><li>This controls relationships at model level and not database level. </li></ul><ul><li>rake db:migrate </li></ul>
  33. 33. Example of Migration <ul><li>class CreateAddresses < ActiveRecord::Migration </li></ul><ul><ul><li>def self.up </li></ul></ul><ul><ul><li>create_table :addresses do |t| </li></ul></ul><ul><ul><ul><li>t.string :street </li></ul></ul></ul><ul><ul><ul><li>t.integer :zip, :default => 0 </li></ul></ul></ul><ul><ul><ul><li>t.references :customer </li></ul></ul></ul><ul><ul><ul><li>t.timestamps </li></ul></ul></ul><ul><ul><li>end </li></ul></ul><ul><ul><li>end </li></ul></ul><ul><ul><li>def self.down </li></ul></ul><ul><ul><li>drop_table :addresses </li></ul></ul><ul><ul><li>end </li></ul></ul><ul><li>end </li></ul>This creates customer_id field in database. Relation between Customer and Address is determined by the models. i.e. class Customer has_one :address
  34. 34. Rake <ul><li>Ruby build program similar to ‘make’ </li></ul><ul><li>Rakefiles (rake‘s version of Makefiles) are completely defined in standard Ruby syntax. </li></ul><ul><ul><li>No XML files to edit. </li></ul></ul><ul><ul><li>No quirky Makefile syntax to worry about (tab or space issues!) </li></ul></ul><ul><li>rake –T in rails environment show default tasks </li></ul><ul><li>User can add new tasks in lib/tasks/filename.rake </li></ul><ul><li>It loads the rails environment – development, production or test or custom. </li></ul>
  35. 35. Part 3 – Hands-on work Building a Rails Application
  36. 36. Ruby on Rails Installation <ul><li>Install ruby on Windows / Linux. </li></ul><ul><ul><li>Latest stable version: Ruby 1.8.6 , 1.8.7 </li></ul></ul><ul><ul><li>Latest version: Ruby 1.9 </li></ul></ul><ul><ul><li>http://rubyonrails.org/download </li></ul></ul><ul><li>Install rubygems </li></ul><ul><ul><li>Link: http:// rubyforge.org/frs/?group_id =126 </li></ul></ul><ul><ul><li>Latest stable version: 1.3.3 </li></ul></ul><ul><li>gem install rails </li></ul><ul><ul><li>Latest stable version: 2.3.2 </li></ul></ul><ul><ul><li>Recommended: 2.1.2 </li></ul></ul><ul><li>Install MySQL 5.x </li></ul><ul><ul><li>Link: http://dev.mysql.com/downloads/mysql/5.1.html#downloads </li></ul></ul>
  37. 37. Setup the Environment <ul><li>Ensure installation is good and versions are correct. </li></ul><ul><ul><li>ruby –v >= 1.8.6 </li></ul></ul><ul><ul><li>gem –v >= 1.3.2 </li></ul></ul><ul><ul><li>rails –v >= 2.1.0 </li></ul></ul><ul><ul><li>mysql –version >= 5.0.x </li></ul></ul><ul><li>Editor: Scite </li></ul><ul><li>Create the rails project </li></ul><ul><ul><li>cmd> rails <name> -d mysql </li></ul></ul>
  38. 38. Rails Project Layout ..../app ......../controller ......../helpers ......../models ......../views ............/layouts ..../config ..../components ..../db ..../doc ..../lib ..../log ..../public ..../script ..../test ..../tmp ..../vendor ......../plugins Core Application code: Controllers, Helpers, Models, Views Configuration for database, initializers,routes Database migrations Additional or custom libraries, rake tasks etc. The HTDOC for this web project. This contains JS, CSS, images etc. External plugins for this project.
  39. 39. Session Break Coffee ?
  40. 40. ActiveRecord Validations <ul><li>validate </li></ul><ul><ul><li>Generic validation method that can be used for custom validation </li></ul></ul><ul><li>validates_uniqueness_of :name </li></ul><ul><li>validates_numericality_of :age </li></ul><ul><li>validates_presence_of :address </li></ul><ul><li>validates_format_of :email, :with => <regex> </li></ul>
  41. 41. ActiveRecord Callbacks <ul><li>before_create </li></ul><ul><li>after_create </li></ul><ul><li>before_save </li></ul><ul><li>after_save </li></ul><ul><li>before_update </li></ul><ul><li>after_update </li></ul><ul><li>before_destroy </li></ul><ul><li>after_destroy </li></ul><ul><li>before_validation </li></ul><ul><li>after_validation </li></ul>
  42. 42. ActiveRecord Relations <ul><li>has_many </li></ul><ul><ul><li>1 ↔ m relationship with child </li></ul></ul><ul><li>belongs_to </li></ul><ul><ul><li>1 ↔ 1 relationship with parent </li></ul></ul><ul><li>has_one </li></ul><ul><ul><li>1 ↔ 1 relationship with child </li></ul></ul><ul><li>has_many :through => </li></ul><ul><ul><li>Earlier versions: has_and_belongs_to_many </li></ul></ul><ul><ul><li>m ↔ m relationship with peer </li></ul></ul>
  43. 43. Database revisit <ul><ul><li>create table `customers` ( </li></ul></ul><ul><ul><ul><li>`id` int(11) auto_increment, </li></ul></ul></ul><ul><ul><ul><li>`name` varchar(64), </li></ul></ul></ul><ul><ul><ul><li>`age`int, </li></ul></ul></ul><ul><ul><li>primary key `id`) </li></ul></ul><ul><ul><li>create table `addresses` ( </li></ul></ul><ul><ul><ul><li>`id` int(11) auto_increment, </li></ul></ul></ul><ul><ul><ul><li>`street` varchar(64), </li></ul></ul></ul><ul><ul><ul><li>`zip_code` varchar(64), </li></ul></ul></ul><ul><ul><ul><li>`customer_id` int, </li></ul></ul></ul><ul><ul><ul><li>foreign key customer_id references customer(id) </li></ul></ul></ul><ul><ul><li>primary key `id`) </li></ul></ul>This line is actually not necessary in Rails as migrations handle this.
  44. 44. has_one ↔ belongs_to <ul><li>class Customer < ActiveRecord::Base </li></ul><ul><li>has_one :address </li></ul><ul><li>end </li></ul><ul><li>class Address < ActiveRecord::Base </li></ul><ul><li>belongs_to :customer </li></ul><ul><li>end </li></ul><ul><li>cust = Customer.new(:name => ‘Gautam Rege’) </li></ul><ul><li>address = Address.new(:customer => cust, </li></ul><ul><li>:street => ‘SB Road’, :zip => ‘411016’) </li></ul><ul><li>cust.address => #<Address object> </li></ul><ul><li>address.customer => # <Customer object> </li></ul><ul><li>Cust.address.zip => Zip code of address for this customer </li></ul>
  45. 45. Database revisit <ul><ul><li>create table `bank_accounts` ( </li></ul></ul><ul><ul><ul><li>`id` int(11) auto_increment, </li></ul></ul></ul><ul><ul><ul><li>`acc_number` varchar(64), </li></ul></ul></ul><ul><ul><ul><li>`branch` varchar(64), </li></ul></ul></ul><ul><ul><ul><li>`customer_id` int, </li></ul></ul></ul><ul><ul><ul><li>foreign key customer_id references customer(id) </li></ul></ul></ul><ul><ul><li>primary key `id`) </li></ul></ul>
  46. 46. has_many ↔ belongs_to <ul><li>class Customer < ActiveRecord::Base </li></ul><ul><li>has_many :bank_accounts </li></ul><ul><li>end </li></ul><ul><li>class BankAccount < ActiveRecord::Base </li></ul><ul><li>belongs_to :customer </li></ul><ul><li>end </li></ul><ul><li>cust = Customer.new(:name => ‘Gautam Rege’) </li></ul><ul><li>bank = BankAccount.new(:customer => cust, </li></ul><ul><li>:acc_number => ‘123456’, :branch => ‘XYZ’) </li></ul><ul><li>cust.bank_accounts =>[ #<BankAccount object> array ] </li></ul><ul><li>bank.customer => # <Customer object> </li></ul>Camelization !!
  47. 47. Database Revist <ul><ul><li>create table `products` ( </li></ul></ul><ul><ul><ul><li>`id` int(11) auto_increment, </li></ul></ul></ul><ul><ul><ul><li>`cost` varchar(64), </li></ul></ul></ul><ul><ul><li>primary key `id`) </li></ul></ul><ul><ul><li>create table `categories` ( </li></ul></ul><ul><ul><ul><li>`id` int(11) auto_increment, </li></ul></ul></ul><ul><ul><ul><li>`name` varchar(64), </li></ul></ul></ul><ul><ul><li>primary key `id`) </li></ul></ul><ul><ul><li>create table `product_categories` ( </li></ul></ul><ul><ul><ul><li>`id` int(11) auto_increment, </li></ul></ul></ul><ul><ul><ul><li>`product_id` int, </li></ul></ul></ul><ul><ul><ul><li>`category_id` int </li></ul></ul></ul><ul><ul><li>primary key `id`) </li></ul></ul>
  48. 48. has_many :through => <ul><li>class Customer < ActiveRecord::Base </li></ul><ul><li>has_many :bank_account_customers </li></ul><ul><li>has_many :bank_accounts :through => :bank_account_customers </li></ul><ul><li>end </li></ul><ul><li>class BankAccount < ActiveRecord::Base </li></ul><ul><li>has_many : bank_account_customers </li></ul><ul><li>has_many :customers :through => : bank_account_customers </li></ul><ul><li>end </li></ul><ul><li>class BankAccountCustomer < ActiveRecord::Base </li></ul><ul><li>belongs_to :bank_account </li></ul><ul><li>belongs_to :customer </li></ul><ul><li>end </li></ul><ul><li>customer.bank_accounts => [ #<BankAccount object> array ] </li></ul><ul><li>acc.customers => [ #<Customer object> array ] </li></ul>
  49. 49. Named Scopes <ul><li>ActiveRecord::NamedScope::Scope </li></ul><ul><li>A scope represents a narrowing of a database query </li></ul><ul><li>Returns a collection but its not an Array. </li></ul><ul><li>It resembles the association object constructed by a has_many declaration </li></ul><ul><li>Unlike arrays, They are “composable” - named_scopes can be chained! </li></ul>
  50. 50. Named Scope example class Customer < ActiveRecord::Base has_many :bank_accounts named_scope :hni, :conditions => [ ‘hni = ?’ true ] named_scope :high_risk lambda do | list | { :joins => ‘risk_customer_lists’, :conditions => [‘name in (?)’, list ] } End @customers = Customer.hni @customers = Customer.hni @customers = @customers.high_risk(terrorists) @customers = Customer.hni.high_risk(terrorists)
  51. 51. Hands On! <ul><li>Creating & updating migrations </li></ul><ul><ul><li>Adding relationships </li></ul></ul><ul><li>Rails console </li></ul><ul><li>Rails dbconsole </li></ul>
  52. 52. Session Break Coffee ?
  53. 53. Part 2.2 ActionController <ul><li>Rails HTTP request processing </li></ul><ul><li>Helpers </li></ul><ul><li>Filters </li></ul><ul><li>Accessing the models </li></ul><ul><li>Rendering the views </li></ul>
  54. 54. Processing a HTTP Rails request <ul><li>http:// host:port /:controller/:action/:id </li></ul><ul><ul><li>http://some.url:3000/customer/show/1 </li></ul></ul><ul><li>“ _controller” suffix in app/controllers </li></ul><ul><ul><li>customers_controller.rb </li></ul></ul><ul><li>All actions are mapped as functions in the controller. “def show” </li></ul><ul><li>params[:id] = 1 </li></ul><ul><li>All views default to app/views/<controller>/<action>.erb.html </li></ul><ul><ul><li>app/views/customers/show.html.erb </li></ul></ul>
  55. 55. Helpers <ul><li>Helpers are not classes but modules. </li></ul><ul><li>They mainly assist views with some helper functions and global etc. </li></ul><ul><li>Helper methods are accessible in controllers and views. </li></ul>Hmm.. Why are helpers not available to the model?
  56. 56. Filters <ul><li>before_filter, after_filter are controller class methods </li></ul><ul><li>Filters can be used to check authentication, caching, or auditing before the intended action is performed. </li></ul><ul><li>Filters have access to the request, response headers </li></ul><ul><li>class CustomerController < ApplicationController </li></ul><ul><li>before_filter :login_required, :except => [:list, :show] </li></ul><ul><li> def login_required </li></ul><ul><li># check if user is logged in </li></ul><ul><li> end </li></ul><ul><li>end </li></ul>
  57. 57. ActionController example <ul><li>app/controllers/customer_controller.rb: </li></ul><ul><li>class CustomerController < ApplicationController </li></ul><ul><li>def index </li></ul><ul><li># default function when no action is called. </li></ul><ul><li>:redirect_to :action => ‘list’ </li></ul><ul><li>end </li></ul><ul><li>def list </li></ul><ul><li>@customers = Customer.find(:all) </li></ul><ul><li>end </li></ul><ul><li>def show </li></ul><ul><li>@customer = Customer.find(params[:id]) </li></ul><ul><li>end </li></ul><ul><li>end </li></ul>GET and POST parameters are accessed via params
  58. 58. Part 2.3 ActionView <ul><li>Embedded Ruby (erb) </li></ul><ul><li>Rails Magic </li></ul><ul><ul><li>Instance variables (@variables) are copied into and ActionView instance before view invocation </li></ul></ul><ul><ul><li>That is why all instance variables created in ActionController are available ‘as is’ to the views. </li></ul></ul>
  59. 59. Partials <ul><li>Partials are views which can be rendered in other views. </li></ul><ul><li>They are always stored with a ‘_’ prefix </li></ul><ul><ul><li>_form.erb.html </li></ul></ul><ul><li>:render :partial => ‘form’ </li></ul>
  60. 60. Layouts <ul><li>The basic page layout for all pages. </li></ul><ul><li>Default layout: application.erb.html </li></ul><ul><li>Layout can be changed by specifying ‘layout <name>’ in the controller. </li></ul>
  61. 61. Rendering Views <ul><li>Embedded Ruby code without rendering </li></ul><ul><ul><li><% %> </li></ul></ul><ul><li>Rendering dynamic data </li></ul><ul><ul><li><%= %> </li></ul></ul><ul><li>Example: </li></ul><ul><ul><li><% @customers.each do |cust| %> </li></ul></ul><ul><ul><ul><li>Name: <%= cust.name %> </li></ul></ul></ul><ul><ul><li><% end %> </li></ul></ul>
  62. 62. FormHelpers <ul><li><% form_for :customer @customer :url => {:action => :create} do |f| %> </li></ul><ul><ul><li><%= f.text_field :name %> </li></ul></ul><ul><ul><li><%= f.date_select :birth_date %> </li></ul></ul><ul><ul><li><%= submit_tag 'Create' %> </li></ul></ul><ul><li><% end %> </li></ul>
  63. 63. Ajax on Rails <ul><li>Link_to_remote </li></ul><ul><li>Remote_form_for </li></ul><ul><li>Rails supports different rendering formats </li></ul><ul><ul><li>Html </li></ul></ul><ul><ul><li>Xml </li></ul></ul><ul><ul><li>Js </li></ul></ul><ul><ul><li>json </li></ul></ul>
  64. 64. Session Break Coffee ?
  65. 65. Building a Rails Application <ul><li>Installing Ruby, rubygems and Rails </li></ul><ul><li>Rails Project Layout </li></ul><ul><li>Design the application </li></ul><ul><li>Write Migrations </li></ul><ul><li>Generate Scaffold </li></ul><ul><li>Deploy & Run </li></ul>Rails helps you build web applications really fast but YOU STILL HAVE TO DESIGN IT !!
  66. 66. Application Idea?? Lets think of one now Pre-decided
  67. 67. Survey Application <ul><li>A survey is a set of questions which a user answers </li></ul><ul><li>Application should have multiple surveys and a user should be able to choose any survey. </li></ul><ul><li>User should be able to see all the questions in the survey. </li></ul><ul><li>User should be able to answer one or more questions. </li></ul><ul><ul><li>User can choose to leave some questions un-answered. </li></ul></ul><ul><li>All answers are free-text </li></ul>
  68. 68. Survey Application <ul><li>Result of the survey for a user should be shown. </li></ul><ul><li>User can edit his previous answer to some question in a survey </li></ul><ul><li>Anyone can see the results of the survey for any user. </li></ul><ul><ul><li>There is no need of any authentication. </li></ul></ul>
  69. 69. Is the above too easy ??  <ul><li>Questions can be free-text or multiple choice. </li></ul><ul><li>User authorization </li></ul><ul><ul><li>User should be able to change only his/her answers later </li></ul></ul><ul><li>Statistical survey data </li></ul><ul><ul><li>How many users took which survey? </li></ul></ul><ul><ul><li>Most popular survey </li></ul></ul><ul><ul><li>User with maximum surveys </li></ul></ul>
  70. 70. Survey Application survey questions answers users
  71. 71. Relationships <ul><li>A survey has_many questions </li></ul><ul><li>A question has_many answers </li></ul><ul><li>A user has_many answers </li></ul><ul><li>A user has_many surveys </li></ul><ul><li>A survey has_many users </li></ul>
  72. 72. Migrations <ul><li>Survey Migration </li></ul><ul><ul><li>t.string :name </li></ul></ul><ul><li>User Migration </li></ul><ul><ul><li>T.string :name </li></ul></ul><ul><li>User_surveys </li></ul><ul><ul><li>T.references :user </li></ul></ul><ul><ul><li>T.references :survey </li></ul></ul>
  73. 73. Migrations contd.. <ul><li>Questions Migration </li></ul><ul><ul><li>T.string value </li></ul></ul><ul><ul><li>T.references :survey </li></ul></ul><ul><li>Answer migration </li></ul><ul><ul><li>T.string :value </li></ul></ul><ul><ul><li>T.references :question </li></ul></ul><ul><ul><li>T.references :user </li></ul></ul>
  74. 74. Scaffolding <ul><li>Generate scaffolds </li></ul><ul><li>./script/generate scaffold Customer </li></ul><ul><ul><li>This generates the model, controller, helper and migration for customer </li></ul></ul><ul><ul><li>app/models/customer.rb </li></ul></ul><ul><ul><li>app/controllers/customers_controller.rb </li></ul></ul><ul><ul><li>App/helpers/customer_helper.rb </li></ul></ul><ul><ul><li>App/views/customers/*.erb.html </li></ul></ul><ul><ul><li>Db/migrate/<version>_create_customers.rb </li></ul></ul>
  75. 75. Checklist <ul><li>Migrations completed? </li></ul><ul><li>Model relationships added? </li></ul><ul><li>Config/database.yml correct? </li></ul><ul><li>Database created? </li></ul><ul><ul><li>rake db:create </li></ul></ul><ul><ul><li>rake db:migrate </li></ul></ul><ul><li>Server started? </li></ul>
  76. 76. Actual Development (finally) <ul><li>Add code to controller </li></ul><ul><li>Add validation to models </li></ul><ul><li>Modify the views </li></ul><ul><li>Adding some CSS and JS </li></ul>
  77. 77. Session Break Coffee ?
  78. 78. Deploying the application <ul><li>Starting rails server </li></ul><ul><ul><li>RAILS_ROOT/script/start </li></ul></ul><ul><li>Stopping the application </li></ul><ul><ul><li>^C </li></ul></ul><ul><li>URL: http://localhost:3000 </li></ul><ul><li>Production Deployment </li></ul><ul><ul><li>./script/server -eproduction </li></ul></ul>
  79. 79. Configuring routes <ul><li>Resource Maps </li></ul><ul><ul><li>map.resources :customer => Customer route </li></ul></ul><ul><ul><ul><li>http://host:port/customers/new </li></ul></ul></ul><ul><ul><ul><li>http://host:port/customers/show </li></ul></ul></ul><ul><ul><ul><li>http://host:port/customers/list </li></ul></ul></ul><ul><li>Named Routes </li></ul><ul><ul><li>map.connect ‘home’, :controller => ‘customers’, :action => ‘list’ </li></ul></ul><ul><li>Default routes </li></ul><ul><ul><li>Map.connect ‘:controller/:action/:id’ </li></ul></ul>
  80. 80. Enterprise Deployment <ul><li>Nginx + mongrel </li></ul><ul><li>Nginx + thin </li></ul><ul><li>Apache + Passenger </li></ul><ul><li>Apache + mongrel </li></ul><ul><li>Capistrano </li></ul>
  81. 81. Capistrano – Rails Deployment <ul><li>Capify </li></ul><ul><li>config/deploy.rb </li></ul><ul><li>cap –T deploy </li></ul><ul><li>cap deploy </li></ul>
  82. 82. Session Break Coffee ?
  83. 83. Advanced Topics <ul><li>Behavior Driven Development </li></ul><ul><li>Test Driven Development </li></ul><ul><li>Rspec </li></ul><ul><li>Merb => Rails 3 </li></ul>
  84. 84. Behaviour Driven Development <ul><li>Standard SDLC process defines this. </li></ul><ul><li>Testing is done after development. </li></ul><ul><ul><li>Unit Testing </li></ul></ul><ul><ul><li>Integration Testing </li></ul></ul><ul><li>Iterative cycle for development and testing. </li></ul><ul><li>Testing is based on development and not requirements </li></ul><ul><li>Takes more time. </li></ul>
  85. 85. Test Driven Development <ul><li>Part of Agile </li></ul><ul><li>Testing and Development go on in parallel </li></ul><ul><ul><li>Actually Test Cases are developed before development !! </li></ul></ul><ul><li>Tests are based on requirements and not on development </li></ul><ul><li>Development is focused on getting tests to pass !  </li></ul>
  86. 86. Rspec <ul><li>Rspec for Models, Controllers and Views </li></ul><ul><li>Books for Rspec are still being written ! </li></ul><ul><li>A lot of specs are clear but clear guidance is missing still </li></ul><ul><li>The Rspec Book – David Chleminsky </li></ul>
  87. 87. Nuances of Rspec <ul><li>Describe => the context or object </li></ul><ul><li>It => test case </li></ul><ul><li>Before and after code </li></ul><ul><li>Helper routines can be added. </li></ul><ul><li>Pending examples (??) </li></ul>
  88. 88. Rspec - Typical Example <ul><ul><li>describe &quot;A new Account&quot; do </li></ul></ul><ul><ul><li>it &quot;should have a balance of 0&quot; do </li></ul></ul><ul><ul><li>account = Account.new </li></ul></ul><ul><ul><li>account.balance.should == Money.new(0, :INR) </li></ul></ul><ul><ul><li>end </li></ul></ul><ul><ul><li>End </li></ul></ul><ul><ul><li># rspec </li></ul></ul><ul><ul><li>A new Account </li></ul></ul><ul><ul><li>- should have a balance 0 </li></ul></ul>
  89. 89. Rspec – Pending Examples <ul><li>Describe “Customer” do </li></ul><ul><ul><li>It “should have a address” </li></ul></ul><ul><ul><li>It “should have name” </li></ul></ul><ul><ul><li>It “should not be on terrorist list” </li></ul></ul><ul><li>Done </li></ul><ul><li>Note that the it() does not have a code block </li></ul>
  90. 90. Before & After Code <ul><li>Before(:each) </li></ul><ul><ul><li>Before each it() executes </li></ul></ul><ul><li>Before(:all) </li></ul><ul><ul><li>Before all its() only once </li></ul></ul><ul><li>After (:each) </li></ul><ul><ul><li>After each (it) completes </li></ul></ul><ul><li>After (:all) </li></ul><ul><ul><li>After all its are complete </li></ul></ul>
  91. 91. Before & after code example <ul><li>Describe Account do </li></ul><ul><ul><li>before(:each) </li></ul></ul><ul><ul><ul><li>@customer = Customer.create(‘Gautam’) </li></ul></ul></ul><ul><ul><ul><li>@account = Account.create(@customer) </li></ul></ul></ul><ul><ul><li>end </li></ul></ul><ul><ul><li>it “should have balance 0” do </li></ul></ul><ul><ul><li>@account.balance.should == Money(0, :INR) </li></ul></ul><ul><ul><li>end </li></ul></ul><ul><li>end </li></ul>
  92. 92. Helper Routines <ul><li>Describe Customer, “when risky” do </li></ul><ul><ul><li>def get_terror_list </li></ul></ul><ul><ul><ul><li>@terror_list = [ ‘Osama’, ‘Laden’, ‘Mahsood’ ] </li></ul></ul></ul><ul><ul><li>end </li></ul></ul><ul><ul><li>it “should have balance 0” do </li></ul></ul><ul><ul><ul><li>get_terror_list </li></ul></ul></ul><ul><ul><ul><li>@customer.include?(@terror_list).should be_empty </li></ul></ul></ul><ul><ul><li>end </li></ul></ul><ul><li>End </li></ul>
  93. 93. Rspec – further reading <ul><li>Shared Examples </li></ul><ul><li>Nested Examples </li></ul><ul><li>Spec::Mock objects </li></ul><ul><li>Writing Views specs </li></ul><ul><li>Writing Model specs </li></ul><ul><li>Writing controller specs </li></ul>
  94. 94. Hands On! <ul><li>rails proj1 -d mysql </li></ul><ul><li>cd proj1/ </li></ul><ul><li>./script/generate rspec </li></ul><ul><li>./script/generate rspec_model Stack </li></ul><ul><li>./script/generate rspec_controller Stack </li></ul><ul><li>rake db:create:all </li></ul><ul><li>RAILS_ENV=test rake db:migrate </li></ul><ul><li>spec spec </li></ul>
  95. 95. References <ul><li>Books </li></ul><ul><ul><li>Rails Recipes – Chad Fowler </li></ul></ul><ul><ul><ul><li>http://www.pragprog.com/titles/fr_rr/rails-recipes </li></ul></ul></ul><ul><ul><li>Agile Web Development with Rails: </li></ul></ul><ul><ul><ul><li>http://www.pragprog.com/titles/rails2/agile-web-development-with-rails </li></ul></ul></ul><ul><li>Internet resources </li></ul><ul><ul><li>http://api.rubyonrails.org </li></ul></ul><ul><ul><li>http://rubyonrails.org/ </li></ul></ul><ul><ul><li>http:// rubyonrails.org /documentation </li></ul></ul>
  96. 96. Thank You!
  1. A particular slide catching your eye?

    Clipping is a handy way to collect important slides you want to go back to later.

×