Ruby on Rails
Rubyhttp://ruby-lang.org
is......a language that focuses on simplicity        puts "hello world"
is......an open source programming            languagehttp://www.ruby-lang.org
is......a language with different       implementations
is...        ...a dynamic languageX = "Hello world"puts x   #outputs "Hello World"X = 10puts x   #outputs "10"
is...      ...an interpreted languageirb(main):001:0> x = "Hello World"=> "Hello World"irb(main):002:0> puts xHello World=...
Running Ruby      via irb (Interactive RuBy):C:Usersuser> irbirb(main):001:0> puts "Hello World"Hello World=> nilirb(main)...
Running Ruby         via ruby command:C:Usersuser> ruby hello.rbHello World
is......a language that focuses on simplicity              Look Ma, no IDE!
is......a language that focuses on simplicity              Ok, there are IDEs
is...    ...an object oriented languageclass Person  def greet    puts "Hello!"  endendp = Person.new()p.hello()
is... ...a "true" object oriented languageputs 1.even?()     #outputs falseputs nil.methods()      #no error!
is......a language that focuses on simplicity puts 1.even?       #outputs false puts nil.methods        #no error!
is...       ...a functional languageemployees = ["Alex", "Bob", "Eve"]employees.each do |employee|  puts "Hello #{employee...
is...       ...a functional languageemps = ["Alex", "Bob", "Eve"]reverse = emps.map { |e| e.reverse }
is...       ...a functional languageemployees = ["Alex", "Bob", "Eve"]emps = employees.sort do |x, y|  x.reverse <=> y.rev...
is...       ...a functional languagehello = Proc.new do |string|  puts "Hello #{string}"endhello.call "Alice"hello.call "B...
is...         ...a flexible languageclass Numeric  def plus(x)    self.+(x)  endendy = 5.plus 6
Ruby Basics
Comments# pound/hash/sharp/octothorpe# for single line comments==beginfor multiline comments* very rare==end
Variablessnake_case = 1 # local variableCamelCase = 200 # constant
Numbersa_number = 1with_delimeter = 1_000_000decimal = 100.01
Auto-convert on Overflowlarge = 1073741823puts large.class #outputs Fixnumlarge = large + 1puts large.class #outputs Bignum
Stringssingle_quote = this stringdouble_quote = "double quote"escape = "double "quote""
String Interpolationputs "20 * 20 = #{20 * 20}"
Symbols:this_is_a_symbol#symbols are like constantsputs "test".object_idputs "test".object_id #differentputs :test.object_...
Operators# Everything works as you expect# +, -, *, /, %, &&, ||, ==, etc# no ++ or --, but theres **# and you could use "...
if - else# no parenthesis neededif x < 0  puts "x   is negative"elsif x >   0  puts "x   is positive"else  puts "x   is ze...
if, single lineputs "x is negative" if x < 0
unlessunless people_count > capacity  puts "There are available seats"end
Arrayslist = [1, "two", 3]list << "another item"list[0] = "uno"puts list[1]
Hashesprices = {:soda => 30, :chips => 5}puts prices[:soda]prices[:rice] = 12.50
Iteration and Blockslist.each { |x| puts x }list.each do |x|  puts xend
More Iteration and Blocksprices.each_pair do |key, value|  puts "#{key}: #{value}"end
More Iteration100.times { puts "Hello" }100.times { |x| puts "Hello #{x}" }100.downto(50) { |y| puts y }
Ranges(1..100).each { |w| puts w }# .. is inclusiveputs (200..300).to_a# .. is right side exclusiveputs (200...300).to_a
Methodsdef greet(name)  puts "Hello #{name}"endgreet "Juan"
Methods, default argumentdef greet(name = "there")  puts "Hello #{name}"endgreet
Methods, variable scopex, y = 2, 1def cube(x)  y = x**3  return yendputs cube(x)puts y
methods, return valuedef cube(x)  y = x**3    #last line is returnedend
OOP: Classesclass Personendp = Person.new
OOP: instance methodsclass Person  def greet    puts "Hello"  endendp = Person.newp.greet
OOP: constructorsclass Person  def initialize    puts "Hello"  endendp = Person.new
OOP: instance variablesclass Person  def initialize(name)    @name = name #var starts with @  endendp = Person.new(name)
OOP: class methodsclass Person  def self.species    "Homo Sapiens"  endendputs Person.species
OOP: class variablesclass Person  def initialize    @@instantiated = true  endend
OOP: getters/settersclass Person  def name=(name)    @name = name #var starts with @  end  def name    name  endendp = Per...
OOP: getters/settersclass Person  attr_accessor :nameendp = Person.newp.name = "Joe"puts p.name
OOP: inheritanceclass Student < Person  attr_accessor :schoolends = Student.news.school = "XYZ High"s.name = "Joe"
Modules#cant be instantiated or subclassedmodule Swimmer  def swim    puts "Im swimming!"  endend
Modules as Mixinmodule Swimmer  def swim    puts "Im swimming!"  endendclass Person  include SwimmerendPerson.new.swim #ou...
Modules for Namespacingmodule X  class D  endendmodule Y  class D  endendX::D.new    #different class from Y::D
Modules for Namespacing# modules and classes are constants!module MyConstants  MeaningOfLife = 42endputs MyConstants::Mean...
Ruby libraries are packaged    and distributed as        RubyGems
Ruby on Railsis a web framework built         in Ruby
pauliwoll
globevisions
InstallingFor this seminar, we will use the     Rails 3.0 installer from        RailsInstaller.org      (Rails Installer v...
Why Rails 3.0 instead of 3.1?
Testing RailsC:Usersuser> cd SitessampleC:Sitessample> rails server
Testing RailsYou should be able to access the server       at http://localhost:3000
Testing RailsAll static files in the /public directory        will now be accessible in          http://localhost:3000
Building your App (Press Ctrl-C to terminate the server)C:Sitessample> cd ..C:Sites> rails new [app_name]C:Sites> cd app_n...
Model View Controller
1               Controller4          3                2    View                        Model   DB
cactusbones
Creating a Controller and a View$ rails generate controller pages demo
Creating a Controller and a View    Start the server via rails server             View the page at  http://localhost:3000/...
The View      Open the erb (Embedded RuBy) file      app/views/pages/demo.html.erb<h1>Pages#demo</h1><p>Find me in app/vie...
Expressions Ruby expressions inside <%= %> are evaluated         and inserted into the HTML<p>2<sup>10</sup> = <%= 2**10 %...
ScriptletsRuby code inside <% %> are executed as-is<ul>  <% 100.times do |x| %>     <li><%= x %></li>  <% end %></ul>
The Controller      app/controllers/pages_controller.rbclass PagesController < ApplicationController  def demo  endend
Instance Variables     instance variables in the controller are         copied when rendering the view#app/controllers/pag...
Parameters       HTTP request parameter data are        accessible via the params hash#app/controllers/pages_controller.rb...
Controller Routing         incoming requests go through              config/routes.rb  to determine which controller/actio...
Controller RoutingYourApp::Application.routes.draw do  # replace get "pages/demo" with this line to  # capture http://loca...
Controller RoutingYourApp::Application.routes.draw do  # delete public/index.html  # and replace the previous example with...
Creating a ModelOpen a new command prompt (no need to stop the server), go to your applications directoryand run the follo...
Modifying the Database             $ rake db:migrateThis will execute the "migration" files generated      along with the ...
Model code inside Controller#app/controllers/pages_controller.rbclass PagesController < ApplicationController  def demo   ...
Cheating with Scaffold  (kasi inaantok na kayo)
Blog in 2 commands$ rails g scaffold blog_entry  title:string entry:text$ rake db:migrateNow go tohttp://localhost:3000/bl...
Something More Complicated$ rails g scaffold deliveryitem:string quantity:integerprice:decimal paid:booleanaddress:text de...
Convention over Configuration
Dont Repeat Yourself        (DRY)
Representational State      Transfer       (REST)
… and thats it.    Please refer to the handoutsif you want more info about Ruby or            Ruby on Rails
Thank you for listening!       Questions? Philippine Ruby Users Group:          pinoyrb.orgme: bryanbibat.net | @bry_bibat
The seminar should befinished at this point but we       still have time... ...**** it, Lets do it LIVE!
Ruby on Rails
Ruby on Rails
Ruby on Rails
Ruby on Rails
Upcoming SlideShare
Loading in …5
×

Ruby on Rails

2,756 views

Published on

SFD 2011 Cavite, STI Southwoods

Published in: Technology
0 Comments
1 Like
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total views
2,756
On SlideShare
0
From Embeds
0
Number of Embeds
12
Actions
Shares
0
Downloads
52
Comments
0
Likes
1
Embeds 0
No embeds

No notes for slide

Ruby on Rails

  1. 1. Ruby on Rails
  2. 2. Rubyhttp://ruby-lang.org
  3. 3. is......a language that focuses on simplicity puts "hello world"
  4. 4. is......an open source programming languagehttp://www.ruby-lang.org
  5. 5. is......a language with different implementations
  6. 6. is... ...a dynamic languageX = "Hello world"puts x #outputs "Hello World"X = 10puts x #outputs "10"
  7. 7. is... ...an interpreted languageirb(main):001:0> x = "Hello World"=> "Hello World"irb(main):002:0> puts xHello World=> nil
  8. 8. Running Ruby via irb (Interactive RuBy):C:Usersuser> irbirb(main):001:0> puts "Hello World"Hello World=> nilirb(main):002:0>
  9. 9. Running Ruby via ruby command:C:Usersuser> ruby hello.rbHello World
  10. 10. is......a language that focuses on simplicity Look Ma, no IDE!
  11. 11. is......a language that focuses on simplicity Ok, there are IDEs
  12. 12. is... ...an object oriented languageclass Person def greet puts "Hello!" endendp = Person.new()p.hello()
  13. 13. is... ...a "true" object oriented languageputs 1.even?() #outputs falseputs nil.methods() #no error!
  14. 14. is......a language that focuses on simplicity puts 1.even? #outputs false puts nil.methods #no error!
  15. 15. is... ...a functional languageemployees = ["Alex", "Bob", "Eve"]employees.each do |employee| puts "Hello #{employee}"end
  16. 16. is... ...a functional languageemps = ["Alex", "Bob", "Eve"]reverse = emps.map { |e| e.reverse }
  17. 17. is... ...a functional languageemployees = ["Alex", "Bob", "Eve"]emps = employees.sort do |x, y| x.reverse <=> y.reverseend
  18. 18. is... ...a functional languagehello = Proc.new do |string| puts "Hello #{string}"endhello.call "Alice"hello.call "Bob"
  19. 19. is... ...a flexible languageclass Numeric def plus(x) self.+(x) endendy = 5.plus 6
  20. 20. Ruby Basics
  21. 21. Comments# pound/hash/sharp/octothorpe# for single line comments==beginfor multiline comments* very rare==end
  22. 22. Variablessnake_case = 1 # local variableCamelCase = 200 # constant
  23. 23. Numbersa_number = 1with_delimeter = 1_000_000decimal = 100.01
  24. 24. Auto-convert on Overflowlarge = 1073741823puts large.class #outputs Fixnumlarge = large + 1puts large.class #outputs Bignum
  25. 25. Stringssingle_quote = this stringdouble_quote = "double quote"escape = "double "quote""
  26. 26. String Interpolationputs "20 * 20 = #{20 * 20}"
  27. 27. Symbols:this_is_a_symbol#symbols are like constantsputs "test".object_idputs "test".object_id #differentputs :test.object_idputs :test.object_id #same
  28. 28. Operators# Everything works as you expect# +, -, *, /, %, &&, ||, ==, etc# no ++ or --, but theres **# and you could use "and" in# place of &&, or "or" <-> ||
  29. 29. if - else# no parenthesis neededif x < 0 puts "x is negative"elsif x > 0 puts "x is positive"else puts "x is zero"end
  30. 30. if, single lineputs "x is negative" if x < 0
  31. 31. unlessunless people_count > capacity puts "There are available seats"end
  32. 32. Arrayslist = [1, "two", 3]list << "another item"list[0] = "uno"puts list[1]
  33. 33. Hashesprices = {:soda => 30, :chips => 5}puts prices[:soda]prices[:rice] = 12.50
  34. 34. Iteration and Blockslist.each { |x| puts x }list.each do |x| puts xend
  35. 35. More Iteration and Blocksprices.each_pair do |key, value| puts "#{key}: #{value}"end
  36. 36. More Iteration100.times { puts "Hello" }100.times { |x| puts "Hello #{x}" }100.downto(50) { |y| puts y }
  37. 37. Ranges(1..100).each { |w| puts w }# .. is inclusiveputs (200..300).to_a# .. is right side exclusiveputs (200...300).to_a
  38. 38. Methodsdef greet(name) puts "Hello #{name}"endgreet "Juan"
  39. 39. Methods, default argumentdef greet(name = "there") puts "Hello #{name}"endgreet
  40. 40. Methods, variable scopex, y = 2, 1def cube(x) y = x**3 return yendputs cube(x)puts y
  41. 41. methods, return valuedef cube(x) y = x**3 #last line is returnedend
  42. 42. OOP: Classesclass Personendp = Person.new
  43. 43. OOP: instance methodsclass Person def greet puts "Hello" endendp = Person.newp.greet
  44. 44. OOP: constructorsclass Person def initialize puts "Hello" endendp = Person.new
  45. 45. OOP: instance variablesclass Person def initialize(name) @name = name #var starts with @ endendp = Person.new(name)
  46. 46. OOP: class methodsclass Person def self.species "Homo Sapiens" endendputs Person.species
  47. 47. OOP: class variablesclass Person def initialize @@instantiated = true endend
  48. 48. OOP: getters/settersclass Person def name=(name) @name = name #var starts with @ end def name name endendp = Person.new(name)p.name = "Joe"
  49. 49. OOP: getters/settersclass Person attr_accessor :nameendp = Person.newp.name = "Joe"puts p.name
  50. 50. OOP: inheritanceclass Student < Person attr_accessor :schoolends = Student.news.school = "XYZ High"s.name = "Joe"
  51. 51. Modules#cant be instantiated or subclassedmodule Swimmer def swim puts "Im swimming!" endend
  52. 52. Modules as Mixinmodule Swimmer def swim puts "Im swimming!" endendclass Person include SwimmerendPerson.new.swim #outputs "Im swimming!"
  53. 53. Modules for Namespacingmodule X class D endendmodule Y class D endendX::D.new #different class from Y::D
  54. 54. Modules for Namespacing# modules and classes are constants!module MyConstants MeaningOfLife = 42endputs MyConstants::MeaningOfLife
  55. 55. Ruby libraries are packaged and distributed as RubyGems
  56. 56. Ruby on Railsis a web framework built in Ruby
  57. 57. pauliwoll
  58. 58. globevisions
  59. 59. InstallingFor this seminar, we will use the Rails 3.0 installer from RailsInstaller.org (Rails Installer v1.3.0)
  60. 60. Why Rails 3.0 instead of 3.1?
  61. 61. Testing RailsC:Usersuser> cd SitessampleC:Sitessample> rails server
  62. 62. Testing RailsYou should be able to access the server at http://localhost:3000
  63. 63. Testing RailsAll static files in the /public directory will now be accessible in http://localhost:3000
  64. 64. Building your App (Press Ctrl-C to terminate the server)C:Sitessample> cd ..C:Sites> rails new [app_name]C:Sites> cd app_name
  65. 65. Model View Controller
  66. 66. 1 Controller4 3 2 View Model DB
  67. 67. cactusbones
  68. 68. Creating a Controller and a View$ rails generate controller pages demo
  69. 69. Creating a Controller and a View Start the server via rails server View the page at http://localhost:3000/pages/demo
  70. 70. The View Open the erb (Embedded RuBy) file app/views/pages/demo.html.erb<h1>Pages#demo</h1><p>Find me in app/views/pages/demo.html.erb</p>
  71. 71. Expressions Ruby expressions inside <%= %> are evaluated and inserted into the HTML<p>2<sup>10</sup> = <%= 2**10 %></p>
  72. 72. ScriptletsRuby code inside <% %> are executed as-is<ul> <% 100.times do |x| %> <li><%= x %></li> <% end %></ul>
  73. 73. The Controller app/controllers/pages_controller.rbclass PagesController < ApplicationController def demo endend
  74. 74. Instance Variables instance variables in the controller are copied when rendering the view#app/controllers/pages_controller.rbclass PagesController < ApplicationController def demo @message = "Hello World" endend#app/views/pages/demo.html.erb<p><%= @message %></p>
  75. 75. Parameters HTTP request parameter data are accessible via the params hash#app/controllers/pages_controller.rbclass PagesController < ApplicationController def demo @message = "Hello #{ params[:name] }" endend# http://localhost:3000/pages/demo?name=John
  76. 76. Controller Routing incoming requests go through config/routes.rb to determine which controller/action should handle itYourApp::Application.routes.draw do get "pages/demo" #all requests to /pages/demo #are handled by the "demo" #action at the PagesController ...
  77. 77. Controller RoutingYourApp::Application.routes.draw do # replace get "pages/demo" with this line to # capture http://localhost:3000/demo instead match "demo" => "pages#demo" ...
  78. 78. Controller RoutingYourApp::Application.routes.draw do # delete public/index.html # and replace the previous example with this to # capture http://localhost:3000/ root :to => "pages#demo" ...
  79. 79. Creating a ModelOpen a new command prompt (no need to stop the server), go to your applications directoryand run the following rails generate command: $ rails generate model visit
  80. 80. Modifying the Database $ rake db:migrateThis will execute the "migration" files generated along with the model that define the DB change to be applied
  81. 81. Model code inside Controller#app/controllers/pages_controller.rbclass PagesController < ApplicationController def demo Visit.create @visit_count = Visit.count @last_visit = Visit.last.created_at endend#app/views/pages/demo.html.erb<p>Visits logged in DB: <%= @visit_count %></p><p>Last Visit: <%= @last_visit %></p>
  82. 82. Cheating with Scaffold (kasi inaantok na kayo)
  83. 83. Blog in 2 commands$ rails g scaffold blog_entry title:string entry:text$ rake db:migrateNow go tohttp://localhost:3000/blog_entries
  84. 84. Something More Complicated$ rails g scaffold deliveryitem:string quantity:integerprice:decimal paid:booleanaddress:text deliver_by:datetime$ rake db:migrateNow go tohttp://localhost:3000/deliveries
  85. 85. Convention over Configuration
  86. 86. Dont Repeat Yourself (DRY)
  87. 87. Representational State Transfer (REST)
  88. 88. … and thats it. Please refer to the handoutsif you want more info about Ruby or Ruby on Rails
  89. 89. Thank you for listening! Questions? Philippine Ruby Users Group: pinoyrb.orgme: bryanbibat.net | @bry_bibat
  90. 90. The seminar should befinished at this point but we still have time... ...**** it, Lets do it LIVE!

×