94
Ruby on Rails

Ruby on Rails

Embed Size (px)

Citation preview

Ruby on Rails

Ruby

http://ruby-lang.org

is...

...a language that focuses on simplicity

puts "hello world"

is...

...an open source programming language

http://www.ruby-lang.org

is...

...a language with different implementations

is...

...a dynamic language

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

is...

...an interpreted language

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

Running Ruby

via irb (Interactive RuBy):

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

Running Ruby

via ruby command:

C:\Users\user> 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 language

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

is...

...a "true" object oriented language

puts 1.even?() #outputs false

puts nil.methods() #no error!

is...

...a language that focuses on simplicity

puts 1.even? #outputs false

puts nil.methods #no error!

is...

...a functional language

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

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

is...

...a functional language

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

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

is...

...a functional language

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

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

is...

...a functional language

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

hello.call "Alice"

hello.call "Bob"

is...

...a flexible language

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

y = 5.plus 6

Ruby Basics

Comments

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

==beginfor multiline comments* very rare==end

Variables

snake_case = 1 # local variable

CamelCase = 200 # constant

Numbers

a_number = 1 with_delimeter = 1_000_000

decimal = 100.01

Auto-convert on Overflow

large = 1073741823

puts large.class #outputs Fixnum

large = large + 1

puts large.class #outputs Bignum

Strings

single_quote = 'this string'

double_quote = "double 'quote'"

escape = "double \"quote\""

String Interpolation

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

Symbols

:this_is_a_symbol

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

Operators

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

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

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

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

if, single line

puts "x is negative" if x < 0

unless

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

Arrays

list = [1, "two", 3]

list << "another item"

list[0] = "uno"

puts list[1]

Hashes

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

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

Iteration and Blocks

list.each { |x| puts x }

list.each do |x| puts xend

More Iteration and Blocks

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

More Iteration

100.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

Methods

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

greet "Juan"

Methods, default argument

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

greet

Methods, variable scope

x, y = 2, 1

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

puts cube(x)puts y

methods, return value

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

OOP: Classes

class Personend

p = Person.new

OOP: instance methods

class Person def greet puts "Hello" endend

p = Person.newp.greet

OOP: constructors

class Person def initialize puts "Hello" endend

p = Person.new

OOP: instance variables

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

p = Person.new(name)

OOP: class methods

class Person def self.species "Homo Sapiens" endend

puts Person.species

OOP: class variables

class Person def initialize @@instantiated = true endend

OOP: getters/setters

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

OOP: getters/setters

class Person attr_accessor :nameend

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

OOP: inheritance

class Student < Person attr_accessor :schoolend

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

Modules

#can't be instantiated or subclassed

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

Modules as Mixin

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

class Person include Swimmerend

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

Modules for Namespacing

module X class D endendmodule Y class D endend

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

Modules for Namespacing

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

puts MyConstants::MeaningOfLife

Ruby libraries are packaged and distributed as

RubyGems

Ruby on Railsis a web framework built

in Ruby

pauliwoll

globevisions

Installing

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

RailsInstaller.org (Rails Installer v1.3.0)

Why Rails 3.0 instead of 3.1?

Testing Rails

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

C:\Sites\sample> rails server

Testing Rails

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

Testing Rails

All 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:\Sites\sample> cd ..

C:\Sites> rails new [app_name]

C:\Sites> cd app_name

Model View Controller

View

Controller

Model DB

1

234

cactusbones

Creating a Controller and a View

$ rails generate controller pages demo

Creating a Controller and a View

Start the server via rails serverView the page at

http://localhost:3000/pages/demo

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>

Expressions

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

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

Scriptlets

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

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

The Controller

app/controllers/pages_controller.rb

class PagesController < ApplicationController def demo end

end

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>

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

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 ...

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" ...

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" ...

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

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

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>

Cheating with Scaffold

(kasi inaantok na kayo)

Blog in 2 commands

$ rails g scaffold blog_entry title:string entry:text

$ rake db:migrate

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

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

Convention over Configuration

Don't Repeat Yourself(DRY)

Representational State Transfer(REST)

… and that's it.

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

Ruby on Rails

Thank you for listening!

Questions?

Philippine Ruby Users Group: pinoyrb.org

me: bryanbibat.net | @bry_bibat

The seminar should be finished at this point but we

still have time...

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