You are on page 1of 88

LOGO

Ruby On Rails
Nhm trnh by: NewWind Khoa CNTT - HKHTN

Ni dung trnh by
1 2 3 4 5 Tng quan v Ruby On Rails Kin trc MVC, lp trnh vi CSDL Qun l Session, Cookies, Mail Scaffolding, Plugins Ajax On Rails

1. Tng quan v Ruby On Rails

Ngun tham kho

http://en.wikipedia.org/wiki/Yukihiro_Matsumoto http://www.ruby-lang.org/ http://www.tutorialspoint.com/ http://www.meshplex.org/wiki/Ruby/Ruby_on_R ails_programming_tutorials

Tng quan v Ruby

Ruby l:
s kt hp thnh cng ca Smalltalk, Python, Perl. Ngn ng lp trnh cp cao. c thng dch ging Perl, Python Hng i tng ging Smalltalk, Java c vit bi Matz nm 1993

Tng quan v Ruby

Mt s c trng ca Ruby:
Hng i tng thun ty D hc tp v nghin cu. M ngun m Rt nhiu th vin Code t, li t Giao tip d dng trong team

Tng quan v Ruby

Yukihiro Matsumoto (Matz)


Sinh ngy: 14 - 04 1965 Quc tch: Nht Ngh nghip: Computer scientist, programmer

Ruby is simple in appearance, but is very complex inside, just like our human body
Matz, speaking on the Ruby-Talk mailing list, May 12th, 2000.

Tng quan v Rails

Rails l:
Web-application framework. c vit bi David Heinemeier Hansson. M ngun m

Tng quan v Rails

David Heinemeier Hansson


Sinh ngy: 15 - 10 1979 Quc tch: M Ngh nghip: programmer

Tng quan v Ruby On Rails

Tng quan v Ruby On Rails

Ci t:
Download InstallRails 2.0 (http://rubyforge.org/frs/?group_id=904) Gii nn tp tin va download vo C:\ Chy file InstallRails trong th mc va gii nn Vo trang http://localhost:3000/ kim tra kt qu

Tng quan v Ruby On Rails

Demo 1: Hello World


Ci t Ruby On Rails

To project ROR
Cu hnh ng dng (ph quyt Active Record) Deploy ng dng

Tng quan v Ruby On Rails

Embeded Ruby
<% %> : Thc thi Ruby code <%= %> : Thc thi Ruby code, v in ra trang HTML Views: phn m rng *.erb hoc *.rhtml Controllers, Models: phn m rng *.rb <%# %> : comment 1 dng <% =begin comment nhiu dng =end %>

Tng quan v Ruby

Variables:
$ten_bien: bin ton cc, c th s dng trong cc class khc nhau @ten_bien: bin thc th, c th s dng trong cc phng thc khc nhau ca 1 class @@ten_bien: bin lp, ging bin static ten_bien: bin local

Pseudo-Variables:
self: ging $this trong PHP nil: ging null trong PHP. <% hello = nil # nu bn cha xc nh c kiu ca bin hello %> <% hello1 = 1 # hello1 l bin kiu Integer %>

Tng quan v Ruby

Types
Integer Numbers, Floating Numbers, Boolean String Literals <%= Multiplication Value : #{24*60*60}; %> Ruby Arrays <% ary = [ "fred", 10, 3.14] for i in ary %> <%= i %> <% end %> Ruby Hashes <% hsh = { "red" => 0xf00, "green" => 0x0f0 } for key, value in hsh %> <%= #{key} is #{value} <br/>" %> <% end %> Ruby Ranges <% for n in 10..15 %> <%= n %> <% end %>

Tng quan v Ruby

Operator
S hc: +, -, *, /, %, So snh: ==, !=, >, >=, <, <=, Gn: =, +=, Logic: &&, ||, !,

Ging C#

Tng quan v Ruby

if .. else
<% x=1 if x > 2 %> <%= x is greater than 2 %> <% elsif x < 2 && x >= 0 %> <%= x is 0, 1 or 2 %> <% else %> <%= x is smaller than 0 %> <% end %>

Tng quan v Ruby

case
<% age = 5 case age when 0 .. 2 %> <%= "baby" %> <% when 3 .. 6 %> <%= little child %> <% when 7 .. 12 %> <%= child %> <% when 13 .. 18 %> <%= youth %> <% else %> <%= adult %> <% end %>

Tng quan v Ruby

while
<% i=0 num = 5 while i < num do %> <%= i = #i) %> <% i +=1 end %>

for
<% for i in 0..5 %> <%= i = #{i} %> <% end %>

<% ary = [ "fred", 10, 3.14] for j in ary %> <%= j = #{j} %> <% end %>

break : thot khi vng lp next : nhy sang bc lp k tip

Tng quan v Ruby

PHP
class Hello [extends Class]{ private $name; public function __construct($s) { $this->name = $s; }

Ruby
class Hello [< Class] def initialize( name ) @name = name end def salute puts "Hello #{@name}!" end End # Create a new object h = Hello.new("Ruby") # Output "Hello Ruby!" h.Salute

public function salute(){ echo Hello $this->name; }

// Create a new object $h = new Hello(Ruby); // Output "Hello Ruby!" $h->salute();

Tng quan v Ruby

Constant :

Ten_hang: l 1 hng s c tn l Ten_hang ?.rb class Inside_two CONST = ' inside two' def where_is_my_CONST CONST end End ?.erb <%= Inside_two.new.where_is_my_CONST %> <%= Inside_two::CONST %>

Tng quan v Ruby On Rails

Demo 2: Cng 2 s
X l Request

Tng tc gia Controller v View

Tng quan v Ruby On Rails

Demo 3: QL loi sch


Kt ni CSDL n gin

Tng tc trong m hnh MVC

2. Ruby On Rails, lp trnh vi CSDL

Gii thiu v Ruby on Rails


Ruby on Rails l mt ng dng vit bng ngn ng Ruby, framework Rail. Ruby on Rails cn c gi tt l Rails hay RoR

Gii thiu v kin trc MVC

Trch nhim mi thnh phn


Model: truy xut, xc nhn, lu tr d liu View: hin th cc thng tin, nhn d liu u vo t ngi dng

Controller: trung gian gia Model v View, nhn yu cu t pha client

ng dng Rails
To Controller (demo) tp>ruby script/generate controller name tp>ruby script/generate controller name action To Model tp>ruby script/generate model name To View

Cu trc th mc Rails
demo/ ..../app ......../controller ......../helpers ......../models ......../views ............../layouts ..../components ..../config ..../db ..../doc ..../lib ..../log ..../public ..../script ..../test ..../tmp ..../vendor README Rakefile

To ng dng Hello world


B1: To ng dng hello tp>rails hello B2: To Controller tp>ruby script/generate controller app B3: To action method B4: To View Demo

Lp trnh vi CSDL
Cu hnh truy cp CSDL
M file database.yml v config nh sau Development: adapter : mysql database : database_name username : root password : host : localhost Test: adapter : mysql database : database_name username : root password : host : localhost

Active Record Model


n gin l th vin dng to v thc thi truy vn, nh x: Cc bng d liu vo cc lp i tng Cc dng d liu vo cc i tng Cc ct d liu vo thuc tnh ca cc i tng S dng Active Record Model, ng dng ca ta s khng cn phi lm vic vi table, column m thay vo s lm vic vi lp, i tng, thuc tnh.

To mi quan h gia cc Model


One-to-Many class Publisher < ActiveRecord::Base has_many :books end Many-to-One class Book < ActiveRecord::Base belongs_to :publisher end Many-to-Many class Book < ActiveRecord::Base has_and_belongs_to_many :authors belongs_to :publisher end

Migration
Thay i ni dung v cu trc lc CSDL Lu vt cc thay i trong lc c s d liu (cc version khc nhau)

Demo

Demo cch thc hot ng

Tr ti action new c nh ngha trong Controller

<%= link_to 'Add a new author', :action => 'new' %>

Demo cch thc hot ng


#phuong thuc nay duoc goi khi ban muon hien trang cho nguoi dung nhap bao cho ng dng Rails biet chung ta se thuc hien them 1 record moi vao trong database def new @author = Author.new @page_title = 'Create new author' end

Khi Action new s render ti trang new.html tng ng

Demo cch thc hot ng


<body> <%= form_tag :action => 'create' %> <p> <label for="author_first_name">First name</label><br/> <%= text_field 'author', 'first_name' %> </p> <p> <label for="author_last_name">Last name</label><br/> <%= text_field 'author', 'last_name' %> </p> <%= submit_tag 'Create' %> <%= form_tag %> <%= link_to 'Back', {:action => 'index'} %> </body>

Demo cch thc hot ng

Thc hin thao tc submit s tr ti action create thng qua HTTP REQUEST

MODEL BIDING

Vn t ra l lm sao HTTP REQUEST c th truyn d liu do ngi dng nhp vo ti cc action method?

Demo cch thc hot ng


u l s khc bit gia 2 dng lnh ny? <%= text_field author', 'first_name' %> <input type=text name=first_name> Dng 1: Kt buc d liu trong text_field vi i tng c t tn l author (tn ty )
Kt buc vy lm g?

Demo cch thc hot ng


Xt action create
def create @author = Author.new(params[:author]) if @author.save :action =>kt 'index' D redirect_to liu truyn t form s buc vi 1 i elsedo ta nh ngha (tn ty ) tng i tng ny c truyn new vo trong params @page_title = 'Create author' dng insert d liu render :action => 'new' Model insert 1 author mi vi d liu c lu end tr trong params end Lu : Tn ca tag phi tuyt i ging vi
thuc tnh nh ngha trong Model

Demo cch thc hot ng


class Author < ActiveRecord::Base has_and_belongs_to_many :books validates_presence_of :first_name, :last_name def name "#{first_name} #{last_name}" end end

Demo
Tm li qu trinh ny thc hin nh sau:
create new.html

new

Model

Controller View

Li ch khi s dng MVC


Ta thy c View v Controller u ph thuc vo Model. Trong khi Model th khng bit g, hay hon ton c lp vi View v Controller Model c th c build v test m khng nh hng hay ph thuc n phn hin th

3. Qun l session, cookies, mail

Session
Sesion l vng nh c to ra t b nh ca server, dng lu tr d liu ca ngi dng (username, password, ). Cch dng: Lu d liu vo session session[:data] = @data Ly d liu t session @data = session[:data]

Cookies
Cookies l mu tin nh c lu trong my ca ngi dng, dng lu tr d liu ca ngi dng (username, password, ) Cch dng: Lu d liu vo session cookies[:data] = @data Ly d liu t session @data = cookies[:data]

Send and Receive Email


Action Mailer l thnh phn c tch hp sn trong ng dng Rails dng gi v nhn mail

Phin bn mi nht ca Action Mailer c th tm thy ti a ch http://rubyforge.org/frs/?group_id=361


Tham kho http://en.wikibooks.org/wiki/Ruby_on_Rails/ActionMailer http://api.rubyonrails.org/files/vendor/rails/actionmailer/README.html http://api.rubyonrails.org/classes/ActionMailer/Base.html

Action mailer configuration


Vo th mc config, m file environment.rb v thm vo cc dng code sau: config.action_mailer.delivery_method = :test|:smtp|:sendmail ActionMailer::Base.smtp_settings = { :address => smtp.example.com", :port => 25, :domain => ".com", :authentication => :login, :user_name => "peter_marklund@fastmail.fm", :password => "..." } config.action_mailer.perform_deliveries = true | false config.action_mailer.default_charset = utf-8"

Generate a Mailer Model


S dng cu lnh sau to 1 mailer ruby script/generate mailer Emailer app\models\emailer.rb class Emailer < ActionMailer::Base end

Mailer Model
class Emailer < ActionMailer::Base def sendmail(recipient, subject, message, sent_at = Time.now) @subject = subject @recipients = recipient @from = 'lsytuan@gmail.com' @sent_on = sent_at @headers = {} @bcc = 'lsytuan@gmail.com' @content_type = "text/html" end end

Mailer View

Ging nh ActionController, mi mailer class cng c 1 view tng ng


sendmail.html.erb Hi! You are having one email message from <%= @email %> with a tilte <%= @title %> and following is the message: <%= @message %> Thanks

Sending Email
To controller cung cp giao din ngi dng ruby script/generate controller Emailer class EmailerController < ApplicationController def sendmail email = params[:email] recipient = email["recipient"] subject = email["subject"] message = email["message"] Emailer.deliver_sendmail(recipient, subject, message) end end

Attachments
class Emailer < ActionMailer::Base def sendmail(recipient, subject, message, sent_at = Time.now, file) @subject = subject @recipients = recipient @from = 'lsytuan@gmail.com' @sent_on = sent_at @headers = {} @bcc = 'lsytuan@gmail.com' @content_type = "text/html unless file.blank? attachment :body => file.read, :filename => file.original_filename end end end

Receive Email
class Emailer < ActionMailer::Base def receive(email) page = Page.find_by_address(email.to.first) page.emails.create( :subject => email.subject, :body => email.body ) if email.has_attachments? for attachment in email.attachments page.attachments.create({ :file => attachment, :description => email.subject }) end end end end

Send and Receive Email

Demo

4. Scaffolding, Plugins

Scaffolding
T ng pht sinh code cho Model, View, Controller Demo

Acts_as_authenticated
acts_as_authenticated plugin, framwork c vit bi cc thnh vin ca cng ty Rick Olson a ch download http://svn.techno-weenie.net/projects/plugins Ci t plugin vo ng dng (demo) To Model v Controller cho chc nng login (demo)

Acts_as_authenticated
acts_as_authenticated c 1 module c gi l AuthenticatedSystem dng chng thc ngi dng AuthenticatedSystem thc thi 1 hm c gi l login_required (yu cu ngi dng nhp username v password trc khi thc thi cc action khc)

Acts_as_authenticated
class ApplicationController < ActionController::Base include AuthenticatedSystem ... end class Admin::BaseController < ApplicationController before_filter :login_required end class Admin::AuthorController < Admin::BaseController ... end

will_paginate
a ch download http://github.com/mislav/will_paginate/tarball/master Chp vo th mc vender\plugins ca ng dng

will_paginate
Cch dng: s dng paginate trong controller def index page = params[:page]; @books = Book.paginate(:page => page, :per_page => 3) end book/index.html.erb <%= will_paginate @books %>

File_column
Plugin h tr vic upload file

a ch download http://opensvn.csie.org/rails_file_column/ plugins/file_column/trunk


Ci t plugin vo ng dng (demo)

File_column
File_column lu tr ng dn ca file c vo trong database

Cch s dng: class Book < ActiveRecord::Base file_column :cover_image end


Thng qua li gi file_column s include hm upload file vo trong Model Model s lu tr ng dn ca file c upload vo ct ca bng bn trong CSDL tng ng

File_column
La chn file upload
<%= file_column_field 'book', "cover_image" %>

Nu file c upload l nh, hin th cn thc hin li gi sau


<%= image_tag url_for_file_column(book, :cover_image) %>

5. Ajax On Rails

Ni dung gii thiu


Ajax truyn thng trong Rails JavaScript Libraries and Prototype Form and Ajax Gii thiu script.aculo.us RJS

Ni dung gii thiu


Ajax truyn thng trong Rails JavaScript Libraries and Prototype Form and Ajax Gii thiu script.aculo.us RJS

Ajax Truyn Thng


S dng i tng XMLHttpRequest

<p><a href="#" onclick="serverSideAlert( );">Call serverside function</a></p> <script type="text/javascript"> function serverSideAlert( ) { var request = new XMLHttpRequest( ); request.open('get', '/chapter2/myresponse', false); request.send(null); alert(request.responseText); } </script>

Ni dung gii thiu


Ajax truyn thng trong Rails JavaScript Libraries and Prototype Form and Ajax Gii thiu script.aculo.us RJS

Th vin javascript
Prototype (Sam Stephenson): cung cp cc hm thc thi ajax) Script.aculo.us (Thomas Fuch): cung cp cc hm x l hiu ng - look and feel

JavaScriptHelper
Module c include vo trong ng dng Rails nh x tt c cc hm chc nng trong prototype thnh cc phng thc c nh ngha trong Rails

Library and Prototype


S dng cc hm th vin trong prototype.js

<script src="/javascripts/prototype.js" type="text/javascript"> </script> <p><a href="#" onclick="prototypeAlert( );">Call with Prototype</a></p> <script type="text/javascript"> function prototypeAlert( ) { new Ajax.Request('/demoajax/myresponse', { onSuccess: function(request) { alert(request.responseText); }}) } </script>

Ajax Link

S dng ajax vi th link_to_remote


Ti u c cch vit ajax gip lm cho m ngun bt cng knh.

<p><%= link_to_remote "Update with Javascript Helper", :url => {:action => "myresponse"}, :update => "response5" %></p> <p id="response5"></p>

Ajax Link

S dng ajax vi th link_to_function


Dng gi thc thi mt hm trong javascript

<div id="target" class="green box"> <div>Here's a DIV with some text.</div> </div> <%= link_to_function "Fade", "new Effect.Fade('target')" %>

Ni dung gii thiu


Ajax truyn thng trong Rails JavaScript Libraries and Prototype Form and Ajax Gii thiu script.aculo.us RJS

Ajax and Form


Mun gi d liu ln server th phi lm sao? s dng form Form non Ajax:

<%= form_tag :action => 'reverse' %> <%= end_form_tag %>

Ajax and Form

S dng form kt hp vi Ajax


Form Ajax Form normal s dng button ajax

Ajax and Form


Form Ajax

<%= form_remote_tag :update => "reversed", :url => { :action => 'reverse' } %> <p>Text to reverse: <%= text_field_tag 'text_to_reverse' %></p> <p id="reversed"></p> <p><%= submit_tag 'Reverse!' %></p> <%= end_form_tag %>

Ajax and Form


Form normal and Button Ajax

<%= form_tag :action => 'reverse' %> <p>Text to reverse: <%= text_field_tag 'text_to_reverse' %></p> <p id="reversed2"></p> <p><%= submit_to_remote 'submit', 'Reverse!', :update => 'reversed2', :url => { :action => 'reverse' } %></p> <%= end_form_tag %>

Ni dung gii thiu


Ajax truyn thng trong Rails JavaScript Libraries and Prototype Form and Ajax Gii thiu script.aculo.us RJS

Script.aculo.us
Ta s dng script.aculo.us to cc hiu ng v drag-drop Visual Effect Drag and Drop

Script.aculo.us
Visual Effect

<div id="target" class="green box"> <div>Here's a DIV with some text.</div> </div> <%= link_to_function "Fade", "new Effect.Fade('target')" %>

Script.aculo.us
Drag and Drop
<div id="drag" class="green box">drag</div> <%= draggable_element :drag, :revert => true %> <div id="drop" class="pink box">drop</div> <%= drop_receiving_element :drop, :hoverclass => "hover", :update => "status", :url => { :action => "receive_drop" } %> <div id="status"></div>

Ni dung gii thiu


Ajax truyn thng trong Rails JavaScript Libraries and Prototype Form and Ajax Gii thiu script.aculo.us RJS

RJS
Ruby-generated JavaScript
Dng pht sinh ra m javascript pha server v gi v li cho trnh duyt.
#external.rjs page.alert "Hello from an RJS file #page.rhtml <p><%= link_to_remote "Alert with external RJS", :url => { :action => "external" } %></p>

Demo ng dng

LOGO