Top Banner
Ruby on Rails
94

Ruby on Rails

Jul 15, 2015

Download

Technology

bryanbibat
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Ruby on Rails

Ruby on Rails

Page 2: Ruby on Rails

Ruby

http://ruby-lang.org

Page 3: Ruby on Rails

is...

...a language that focuses on simplicity

puts "hello world"

Page 4: Ruby on Rails

is...

...an open source programming language

http://www.ruby-lang.org

Page 5: Ruby on Rails

is...

...a language with different implementations

Page 6: Ruby on Rails

is...

...a dynamic language

X = "Hello world"puts x #outputs "Hello World"X = 10puts x #outputs "10"

Page 7: Ruby on Rails

is...

...an interpreted language

irb(main):001:0> x = "Hello World"=> "Hello World"irb(main):002:0> puts xHello World=> nil

Page 8: Ruby on Rails

Running Ruby

via irb (Interactive RuBy):

C:\Users\user> irbirb(main):001:0> puts "Hello World"Hello World=> nilirb(main):002:0>

Page 9: Ruby on Rails

Running Ruby

via ruby command:

C:\Users\user> ruby hello.rbHello World

Page 10: Ruby on Rails

is...

...a language that focuses on simplicity

Look Ma, no IDE!

Page 11: Ruby on Rails

is...

...a language that focuses on simplicity

Ok, there are IDEs

Page 12: Ruby on Rails

is...

...an object oriented language

class Person def greet puts "Hello!" endendp = Person.new()p.hello()

Page 13: Ruby on Rails

is...

...a "true" object oriented language

puts 1.even?() #outputs false

puts nil.methods() #no error!

Page 14: Ruby on Rails

is...

...a language that focuses on simplicity

puts 1.even? #outputs false

puts nil.methods #no error!

Page 15: Ruby on Rails

is...

...a functional language

employees = ["Alex", "Bob", "Eve"]

employees.each do |employee| puts "Hello #{employee}"end

Page 16: Ruby on Rails

is...

...a functional language

emps = ["Alex", "Bob", "Eve"]

reverse = emps.map { |e| e.reverse }

Page 17: Ruby on Rails

is...

...a functional language

employees = ["Alex", "Bob", "Eve"]

emps = employees.sort do |x, y| x.reverse <=> y.reverseend

Page 18: Ruby on Rails

is...

...a functional language

hello = Proc.new do |string| puts "Hello #{string}"end

hello.call "Alice"

hello.call "Bob"

Page 19: Ruby on Rails

is...

...a flexible language

class Numeric def plus(x) self.+(x) endend

y = 5.plus 6

Page 20: Ruby on Rails

Ruby Basics

Page 21: Ruby on Rails

Comments

# pound/hash/sharp/octothorpe# for single line comments

==beginfor multiline comments* very rare==end

Page 22: Ruby on Rails

Variables

snake_case = 1 # local variable

CamelCase = 200 # constant

Page 23: Ruby on Rails

Numbers

a_number = 1 with_delimeter = 1_000_000

decimal = 100.01

Page 24: Ruby on Rails

Auto-convert on Overflow

large = 1073741823

puts large.class #outputs Fixnum

large = large + 1

puts large.class #outputs Bignum

Page 25: Ruby on Rails

Strings

single_quote = 'this string'

double_quote = "double 'quote'"

escape = "double \"quote\""

Page 26: Ruby on Rails

String Interpolation

puts "20 * 20 = #{20 * 20}"

Page 27: Ruby on Rails

Symbols

:this_is_a_symbol

#symbols are like constantsputs "test".object_idputs "test".object_id #differentputs :test.object_idputs :test.object_id #same

Page 28: Ruby on Rails

Operators

# Everything works as you expect# +, -, *, /, %, &&, ||, ==, etc

# no ++ or --, but there's **

# and you could use "and" in# place of &&, or "or" <-> ||

Page 29: Ruby on Rails

if - else

# no parenthesis needed

if x < 0 puts "x is negative"elsif x > 0 puts "x is positive"else puts "x is zero"end

Page 30: Ruby on Rails

if, single line

puts "x is negative" if x < 0

Page 31: Ruby on Rails

unless

unless people_count > capacity puts "There are available seats"end

Page 32: Ruby on Rails

Arrays

list = [1, "two", 3]

list << "another item"

list[0] = "uno"

puts list[1]

Page 33: Ruby on Rails

Hashes

prices = {:soda => 30, :chips => 5}

puts prices[:soda]prices[:rice] = 12.50

Page 34: Ruby on Rails

Iteration and Blocks

list.each { |x| puts x }

list.each do |x| puts xend

Page 35: Ruby on Rails

More Iteration and Blocks

prices.each_pair do |key, value| puts "#{key}: #{value}"end

Page 36: Ruby on Rails

More Iteration

100.times { puts "Hello" }

100.times { |x| puts "Hello #{x}" }

100.downto(50) { |y| puts y }

Page 37: Ruby on Rails

Ranges

(1..100).each { |w| puts w }

# .. is inclusiveputs (200..300).to_a

# .. is right side exclusiveputs (200...300).to_a

Page 38: Ruby on Rails

Methods

def greet(name) puts "Hello #{name}"end

greet "Juan"

Page 39: Ruby on Rails

Methods, default argument

def greet(name = "there") puts "Hello #{name}"end

greet

Page 40: Ruby on Rails

Methods, variable scope

x, y = 2, 1

def cube(x) y = x**3 return yend

puts cube(x)puts y

Page 41: Ruby on Rails

methods, return value

def cube(x) y = x**3 #last line is returnedend

Page 42: Ruby on Rails

OOP: Classes

class Personend

p = Person.new

Page 43: Ruby on Rails

OOP: instance methods

class Person def greet puts "Hello" endend

p = Person.newp.greet

Page 44: Ruby on Rails

OOP: constructors

class Person def initialize puts "Hello" endend

p = Person.new

Page 45: Ruby on Rails

OOP: instance variables

class Person def initialize(name) @name = name #var starts with @ endend

p = Person.new(name)

Page 46: Ruby on Rails

OOP: class methods

class Person def self.species "Homo Sapiens" endend

puts Person.species

Page 47: Ruby on Rails

OOP: class variables

class Person def initialize @@instantiated = true endend

Page 48: Ruby on Rails

OOP: getters/setters

class Person def name=(name) @name = name #var starts with @ end def name name endendp = Person.new(name)p.name = "Joe"

Page 49: Ruby on Rails

OOP: getters/setters

class Person attr_accessor :nameend

p = Person.newp.name = "Joe"puts p.name

Page 50: Ruby on Rails

OOP: inheritance

class Student < Person attr_accessor :schoolend

s = Student.news.school = "XYZ High"s.name = "Joe"

Page 51: Ruby on Rails

Modules

#can't be instantiated or subclassed

module Swimmer def swim puts "I'm swimming!" endend

Page 52: Ruby on Rails

Modules as Mixin

module Swimmer def swim puts "I'm swimming!" endend

class Person include Swimmerend

Person.new.swim #outputs "I'm swimming!"

Page 53: Ruby on Rails

Modules for Namespacing

module X class D endendmodule Y class D endend

X::D.new #different class from Y::D

Page 54: Ruby on Rails

Modules for Namespacing

# modules and classes are constants!module MyConstants MeaningOfLife = 42end

puts MyConstants::MeaningOfLife

Page 55: Ruby on Rails

Ruby libraries are packaged and distributed as

RubyGems

Page 56: Ruby on Rails
Page 57: Ruby on Rails
Page 58: Ruby on Rails
Page 59: Ruby on Rails

Ruby on Railsis a web framework built

in Ruby

Page 60: Ruby on Rails

pauliwoll

Page 61: Ruby on Rails

globevisions

Page 62: Ruby on Rails

Installing

For this seminar, we will use the Rails 3.0 installer from

RailsInstaller.org (Rails Installer v1.3.0)

Page 63: Ruby on Rails

Why Rails 3.0 instead of 3.1?

Page 64: Ruby on Rails
Page 65: Ruby on Rails

Testing Rails

C:\Users\user> cd \Sites\sample

C:\Sites\sample> rails server

Page 66: Ruby on Rails

Testing Rails

You should be able to access the server at http://localhost:3000

Page 67: Ruby on Rails

Testing Rails

All static files in the /public directory will now be accessible in

http://localhost:3000

Page 68: Ruby on Rails

Building your App

(Press Ctrl-C to terminate the server)

C:\Sites\sample> cd ..

C:\Sites> rails new [app_name]

C:\Sites> cd app_name

Page 69: Ruby on Rails

Model View Controller

Page 70: Ruby on Rails

View

Controller

Model DB

1

234

Page 71: Ruby on Rails

cactusbones

Page 72: Ruby on Rails

Creating a Controller and a View

$ rails generate controller pages demo

Page 73: Ruby on Rails

Creating a Controller and a View

Start the server via rails serverView the page at

http://localhost:3000/pages/demo

Page 74: Ruby on Rails

The View

Open the erb (Embedded RuBy) fileapp/views/pages/demo.html.erb

<h1>Pages#demo</h1><p>Find me in app/views/pages/demo.html.erb</p>

Page 75: Ruby on Rails

Expressions

Ruby expressions inside <%= %> are evaluated and inserted into the HTML

<p>2<sup>10</sup> = <%= 2**10 %></p>

Page 76: Ruby on Rails

Scriptlets

Ruby code inside <% %> are executed as-is

<ul> <% 100.times do |x| %> <li><%= x %></li> <% end %></ul>

Page 77: Ruby on Rails

The Controller

app/controllers/pages_controller.rb

class PagesController < ApplicationController def demo end

end

Page 78: Ruby on Rails

Instance Variablesinstance 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>

Page 79: Ruby on Rails

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

Page 80: Ruby on Rails

Controller Routing

incoming requests go throughconfig/routes.rb

to determine which controller/action should handle it

YourApp::Application.routes.draw do

get "pages/demo" #all requests to /pages/demo #are handled by the "demo" #action at the PagesController ...

Page 81: Ruby on Rails

Controller Routing

YourApp::Application.routes.draw do

# replace get "pages/demo" with this line to # capture http://localhost:3000/demo instead match "demo" => "pages#demo" ...

Page 82: Ruby on Rails

Controller Routing

YourApp::Application.routes.draw do

# delete public/index.html # and replace the previous example with this to # capture http://localhost:3000/ root :to => "pages#demo" ...

Page 83: Ruby on Rails

Creating a Model

Open a new command prompt (no need to stop the server), go to your application's directory

and run the following rails generate command:

$ rails generate model visit

Page 84: Ruby on Rails

Modifying the Database

$ rake db:migrate

This will execute the "migration" files generated along with the model that define the

DB change to be applied

Page 85: Ruby on Rails

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>

Page 86: Ruby on Rails

Cheating with Scaffold

(kasi inaantok na kayo)

Page 87: Ruby on Rails

Blog in 2 commands

$ rails g scaffold blog_entry title:string entry:text

$ rake db:migrate

Now go to http://localhost:3000/blog_entries

Page 88: Ruby on Rails

Something More Complicated

$ rails g scaffold delivery item:string quantity:integerprice:decimal paid:booleanaddress:text deliver_by:datetime

$ rake db:migrate

Now go to http://localhost:3000/deliveries

Page 89: Ruby on Rails

Convention over Configuration

Page 90: Ruby on Rails

Don't Repeat Yourself(DRY)

Page 91: Ruby on Rails

Representational State Transfer(REST)

Page 92: Ruby on Rails

… and that's it.

Please refer to the handouts if you want more info about Ruby or

Ruby on Rails

Page 93: Ruby on Rails

Thank you for listening!

Questions?

Philippine Ruby Users Group: pinoyrb.org

me: bryanbibat.net | @bry_bibat

Page 94: Ruby on Rails

The seminar should be finished at this point but we

still have time...

...**** it, Let's do it LIVE!