seminar ruby

88
LOGO Ruby On Rails Nhóm trình bày: NewWind Khoa CNTT - ĐHKHTN

Upload: shinichi-kudo

Post on 13-Apr-2015

25 views

Category:

Documents


2 download

TRANSCRIPT

Page 1: Seminar Ruby

LOGO

Ruby On RailsRuby On Rails

Nhóm trình bày: NewWindKhoa CNTT - ĐHKHTN

Page 2: Seminar Ruby

Nội dung trình bày

Tổng quan về Ruby On Rails1

Kiến trúc MVC, lập trình với CSDL2

Quản lý Session, Cookies, Mail3

Scaffolding, Plugins4

Ajax On Rails5

Page 3: Seminar Ruby

1. Tổng quan về Ruby On Rails

Page 4: Seminar Ruby

Nguồn tham khảo

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

s_programming_tutorials

Page 5: Seminar Ruby

Tổng quan về Ruby

Ruby là:

sự kết hợp thành công của Smalltalk, Python, Perl. Ngôn ngữ lập trình cấp cao. Được thông dịch giống Perl, Python Hướng đối tượng giống Smalltalk, Java Được viết bởi Matz năm 1993

Page 6: Seminar Ruby

Tổng quan về Ruby

Một số đặc trưng của Ruby: Hướng đối tượng thuần túy Dễ học tập và nghiên cứu. Mã nguồn mỡ Rất nhiều thư viện Code ít, lỗi ít Giao tiếp dễ dàng trong team

Page 7: Seminar Ruby

Tổng quan về Ruby

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

Yukihiro Matsumoto (Matz)

Sinh ngày: 14 - 04 – 1965 Quốc tịch: Nhật Nghề nghiệp: Computer scientist,

programmer

Page 8: Seminar Ruby

Rails là: Web-application framework. Được viết bởi David Heinemeier Hansson. Mã nguồn mở

Tổng quan về Rails

Page 9: Seminar Ruby

Tổng quan về Rails

David Heinemeier Hansson

Sinh ngày: 15 - 10 – 1979 Quốc tịch: Mỹ Nghề nghiệp: programmer

Page 10: Seminar Ruby

Tổng quan về Ruby On Rails

Page 11: Seminar Ruby

Tổng quan về Ruby On Rails

Cài đặt: Download InstallRails 2.0 (http://rubyforge.org/frs/?group_id=904)

Giải nén tập tin vừa download vào C:\

Chạy file InstallRails trong thư mục vừa giải nén

Vào trang http://localhost:3000/ kiểm tra kết quả

Page 12: Seminar Ruby

Tổng quan về Ruby On Rails

Demo 1: Hello World Cài đặt Ruby On Rails

Tạo project ROR

Cấu hình ứng dụng (phủ quyết Active Record)

Deploy ứng dụng

Page 13: Seminar Ruby

Tổng quan về Ruby On Rails

Embeded Ruby <% … %> : Thực thi Ruby code <%= … %> : Thực thi Ruby code, và in ra trang HTML

Views: phần mở rộng *.erb hoặc *.rhtml Controllers, Models: phần mở rộng *.rb

<%# … %> : comment 1 dòng <% =begin … comment nhiều dòng =end %>

Page 14: Seminar Ruby

Tổng quan về Ruby

Variables: $ten_bien: biến toàn cục, có thể sử dụng trong các class khác nhau @ten_bien: biến thực thể, có thể sử dụng trong các phương thức khác nhau của 1 class @@ten_bien: biến lớp, giống biến static ten_bien: biến local

Pseudo-Variables: self: giống $this trong PHP nil: giống null trong PHP. …

<% hello = nil # nếu bạn chưa xác định được kiểu của biến hello %><% hello1 = 1 # hello1 là biến kiểu Integer %>

Page 15: Seminar Ruby

Tổng 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 %>

Page 16: Seminar Ruby

Tổng quan về Ruby

Operator

Số học: +, -, *, /, %, … So sánh: ==, !=, >, >=, <, <=, … Gán: =, +=, … Logic: &&, ||, !, …

Giống C#Giống C#

Page 17: Seminar Ruby

Tổng 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 %>

Page 18: Seminar Ruby

Tổng 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 %>

Page 19: Seminar Ruby

Tổng 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 : thoát khỏi vòng lặp next : nhảy sang bước lặp kế tiếp

Page 20: Seminar Ruby

Tổng quan về Ruby

Rubyclass Hello [< Class] def initialize( name ) @name = name end

def salute puts "Hello #{@name}!" endEnd

# Create a new objecth = Hello.new("Ruby")# Output "Hello Ruby!"h.Salute

PHPclass Hello [extends Class]{ private $name; public function __construct($s) { $this->name = $s; } public function salute(){ echo “Hello $this->name”; }}

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

Page 21: Seminar Ruby

Tổng quan về Ruby

Constant : Ten_hang: là 1 hằng số có tên là Ten_hang

?.rbclass Inside_two CONST = ' inside two' def where_is_my_CONST CONST end End

?.erb<%=Inside_two.new.where_is_my_CONST%>

<%=Inside_two::CONST %>

Page 22: Seminar Ruby

Tổng quan về Ruby On Rails

Demo 2: Cộng 2 số Xử lý Request

Tương tác giữa Controller và View

Page 23: Seminar Ruby

Tổng quan về Ruby On Rails

Demo 3: QL loại sách Kết nối CSDL đơn giản

Tương tác trong mô hình MVC

Page 24: Seminar Ruby

2. Ruby On Rails, lập trình với CSDL

Page 25: Seminar Ruby

Giới thiệu về Ruby on Rails

Ruby on Rails là một ứng dụng viết bằng ngôn ngữ Ruby, framework Rail.

Ruby on Rails còn được gọi tắt là Rails hay RoR

Page 26: Seminar Ruby

Giới thiệu về kiến trúc MVC

Page 27: Seminar Ruby

Trách nhiệm mỗi thành phần

Model: truy xuất, xác nhận, lưu trữ dữ liệu

View: hiển thị các thông tin, nhận dữ liệu đầu vào từ người dùng

Controller: trung gian giữa Model và View, nhận yêu cầu từ phía client

Page 28: Seminar Ruby

Ứng dụng Rails

Tạo Controller (demo)tp>ruby script/generate controller

nametp>ruby script/generate controller

name action Tạo Model

tp>ruby script/generate model name Tạo View

Page 29: Seminar Ruby

Cấu trúc thư mục Rails

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

Page 30: Seminar Ruby

Tạo ứng dụng Hello world

B1: Tạo ứng dụng hellotp>rails helloB2: Tạo Controllertp>ruby script/generate controller

appB3: Tạo action methodB4: Tạo View

Demo

Page 31: Seminar Ruby

Lập trình với CSDL

Cấu hình để truy cập CSDL Mở file database.yml và config như sau Development:

adapter : mysqldatabase : database_nameusername : rootpassword :host : localhost

Test:adapter : mysqldatabase : database_nameusername : rootpassword :host : localhost

Page 32: Seminar Ruby

Active Record Model

Đơn giản là thư viện dùng để tạo và thực thi truy vấn, ánh xạ: Các bảng dữ liệu vào các lớp đối tượng Các dòng dữ liệu vào các đối tượng Các cột dữ liệu vào thuộc tính của các

đối tượng

Sử dụng Active Record Model, ứng dụng của ta sẽ không cần phải làm việc với table, column mà thay vào đó sẽ làm việc với lớp, đối tượng, thuộc tính.

Page 33: Seminar Ruby

Tạo mối quan hệ giữa các Model

One-to-Many class Publisher < ActiveRecord::Base has_many :booksend

Many-to-Oneclass Book < ActiveRecord::Base belongs_to :publisherend

Many-to-Manyclass Book < ActiveRecord::Base has_and_belongs_to_many :authors belongs_to :publisherend

Page 34: Seminar Ruby

Migration

Thay đổi nội dung và cấu trúc lược đồ CSDL

Lưu vết các thay đổi trong lược đồ cơ sở dữ liệu (các version khác nhau)

Demo

Page 35: Seminar Ruby

Demo cách thức hoạt động

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

Trỏ tới action new được định nghĩa trong Controller

Trỏ tới action new được định nghĩa trong Controller

Page 36: Seminar Ruby

Demo cách thức hoạt động

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

Khi đó Action new sẽ render tới trang new.html tương ứng

Page 37: Seminar Ruby

Demo cách thức hoạt độ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>

Page 38: Seminar Ruby

Demo cách thức hoạt động

Thực hiện thao tác submit sẽ trỏ tới action create

thông qua HTTP REQUEST

Thực hiện thao tác submit sẽ trỏ tới action create

thông qua HTTP REQUEST

Vấn đề đặt ra là làm sao để HTTP REQUEST có thể truyền dữ liệu do

người dùng nhập vào tới các action method?

Vấn đề đặt ra là làm sao để HTTP REQUEST có thể truyền dữ liệu do

người dùng nhập vào tới các action method?

MODEL BIDING

Page 39: Seminar Ruby

Demo cách thức hoạt động

Đâu là sự khác biệt giữa 2 dòng lệnh này? <%= text_field ‘author', 'first_name' %><input type=”text” name=”first_name”>

Dòng 1: Kết buộc dữ liệu trong text_field với đối tượng được đặt tên là author (tên tùy ý)

Kết buộc vậy để làm gì?Kết buộc vậy để làm gì?

Page 40: Seminar Ruby

Demo cách thức hoạt động

Xét action create

def create @author = Author.new(params[:author]) if @author.save redirect_to :action => 'index' else @page_title = 'Create new author' render :action => 'new' endend

• Dữ liệu truyền từ form sẽ kết buộc với 1 đối tượng do ta định nghĩa (tên tùy ý)• Đối tượng này được truyền vào trong params dùng để insert dữ liệu• Model insert 1 author mới với dữ liệu được lưu trữ trong paramsLưu ý: Tên của tag phải tuyệt đối giống với thuộc tính định nghĩa trong Model

• Dữ liệu truyền từ form sẽ kết buộc với 1 đối tượng do ta định nghĩa (tên tùy ý)• Đối tượng này được truyền vào trong params dùng để insert dữ liệu• Model insert 1 author mới với dữ liệu được lưu trữ trong paramsLưu ý: Tên của tag phải tuyệt đối giống với thuộc tính định nghĩa trong Model

Page 41: Seminar Ruby

Demo cách thức hoạt động

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

Page 42: Seminar Ruby

Demo

Tóm lại quá trinh này thực hiện như sau:

new

new.html

create

Controller

View

Model

Page 43: Seminar Ruby

Lợi ích khi sử dụng MVC

Ta thấy cả View và Controller đều phụ thuộc vào Model. Trong khi Model thì không biết gì, hay hoàn toàn độc lập với View và Controller Model có thể được build và test mà không ảnh hưởng hay phụ thuộc đến phần hiển thị

Page 44: Seminar Ruby

3. Quản lý session, cookies, mail

Page 45: Seminar Ruby

Session

Sesion là vùng nhớ được tạo ra từ bộ nhớ của server, dùng để lưu trữ dữ liệu của người dùng (username, password, …).

Cách dùng: Lưu dữ liệu vào session

session[:data] = @data Lấy dữ liệu từ session

@data = session[:data]

Page 46: Seminar Ruby

Cookies

Cookies là mẩu tin nhỏ được lưu trong máy của người dùng, dùng để lưu trữ dữ liệu của người dùng (username, password, …)

Cách dùng: Lưu dữ liệu vào session

cookies[:data] = @data Lấy dữ liệu từ session

@data = cookies[:data]

Page 47: Seminar Ruby

Send and Receive Email

Action Mailer là thành phần được tích hợp sẵn trong ứng dụng Rails dùng để gởi và nhận mail

Phiên bản mới nhất của Action Mailer có thể tìm thấy tại địa chỉhttp://rubyforge.org/frs/?group_id=361

Tham khảohttp://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

Page 48: Seminar Ruby

Action mailer configuration

Vào thư mục config, mở file environment.rb và thêm vào các dòng 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 => "[email protected]",    :password => "..."   }  config.action_mailer.perform_deliveries = true | false  config.action_mailer.default_charset = “utf-8"

Page 49: Seminar Ruby

Generate a Mailer Model

Sử dụng câu lệnh sau để tạo 1 mailerruby script/generate mailer Emailer

app\models\emailer.rbclass Emailer < ActionMailer::Base end

Page 50: Seminar Ruby

Mailer Model

class Emailer < ActionMailer::Base def sendmail(recipient, subject, message, sent_at =

Time.now) @subject = subject @recipients = recipient @from = '[email protected]' @sent_on = sent_at @headers = {} @bcc = '[email protected]' @content_type = "text/html" endend

Page 51: Seminar Ruby

Mailer View

Giống như ActionController, mỗi mailer class cũng có 1 view tương ứng

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

@message %> Thanks

Page 52: Seminar Ruby

Sending Email

Tạo controller cung cấp giao diện người dùngruby 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

Page 53: Seminar Ruby

Attachments

class Emailer < ActionMailer::Base def sendmail(recipient, subject, message, sent_at = Time.now,

file) @subject = subject @recipients = recipient @from = '[email protected]' @sent_on = sent_at @headers = {} @bcc = '[email protected]' @content_type = "text/html“

unless file.blank? attachment :body => file.read, :filename =>

file.original_filename end

endend

Page 54: Seminar Ruby

Receive Email

class Emailer < ActionMailer::Basedef 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

Page 55: Seminar Ruby

Send and Receive Email

Demo

Page 56: Seminar Ruby

4. Scaffolding, Plugins

Page 57: Seminar Ruby

Scaffolding

Tự động phát sinh code cho Model, View, Controller

Demo

Page 58: Seminar Ruby

Acts_as_authenticated

acts_as_authenticated plugin, framwork được viết bởi các thành viên của công ty Rick Olson

Địa chỉ download

http://svn.techno-weenie.net/projects/plugins

Cài đặt plugin vào ứng dụng (demo)

Tạo Model và Controller cho chức năng login (demo)

Page 59: Seminar Ruby

Acts_as_authenticated

acts_as_authenticated có 1 module được gọi là AuthenticatedSystem dùng để chứng thực người dùng

AuthenticatedSystem thực thi 1 hàm được gọi là login_required (yêu cầu người dùng nhập username và password trước khi thực thi các action khác)

Page 60: Seminar Ruby

Acts_as_authenticated

class ApplicationController < ActionController::Base

include AuthenticatedSystem ...end

class Admin::BaseController < ApplicationController

before_filter :login_requiredend

class Admin::AuthorController < Admin::BaseController

...end

Page 61: Seminar Ruby

will_paginate

Địa chỉ download

http://github.com/mislav/will_paginate/tarball/master

Chép vào thư mục vender\plugins của ứng dụng

Page 62: Seminar Ruby

will_paginate

Cách dùng: sử dụng paginate trong controllerdef index

page = params[:page];@books = Book.paginate(:page =>

page, :per_page => 3)end

book/index.html.erb<%= will_paginate @books %>

Page 63: Seminar Ruby

File_column

Plugin hỗ trợ việc upload file

Địa chỉ download

http://opensvn.csie.org/rails_file_column/ plugins/file_column/trunk

Cài đặt plugin vào ứng dụng (demo)

Page 64: Seminar Ruby

File_column

File_column lưu trữ đường dẫn của file được vào trong database

Cách sử dụng:class Book < ActiveRecord::Base

file_column :cover_image…

end

Thông qua lời gọi file_column sẽ include hàm upload file vào trong Model Model sẽ lưu trữ đường dẫn của file được upload vào cột của bảng bên trong CSDL tương ứng

Page 65: Seminar Ruby

File_column

Lựa chọn file để upload

<%= file_column_field 'book', "cover_image" %>

Nếu file được upload là ảnh, để hiện thị cần thực hiện lời gọi sau<%= image_tag url_for_file_column(book, :cover_image) %>

Page 66: Seminar Ruby

5. Ajax On Rails

Page 67: Seminar Ruby

Nội dung giới thiệu

Ajax truyền thống trong Rails JavaScript Libraries and Prototype Form and Ajax Giới thiệu script.aculo.us RJS

Page 68: Seminar Ruby

Nội dung giới thiệu

Ajax truyền thống trong Rails JavaScript Libraries and Prototype Form and Ajax Giới thiệu script.aculo.us RJS

Page 69: Seminar Ruby

Sử dụng đối tượng XMLHttpRequest

<p><a href="#" onclick="serverSideAlert( );">Call server-side 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>

Ajax Truyền Thống

Page 70: Seminar Ruby

Nội dung giới thiệu

Ajax truyền thống trong Rails JavaScript Libraries and Prototype Form and Ajax Giới thiệu script.aculo.us RJS

Page 71: Seminar Ruby

Thư viện javascript

Prototype (Sam Stephenson): cung cấp các hàm thực thi ajax)

Script.aculo.us (Thomas Fuch): cung cấp các hàm xử lý hiệu ứng - look and feel

Page 72: Seminar Ruby

JavaScriptHelper

Module được include vào trong ứng dụng Rails

Ánh xạ tất cả các hàm chức năng trong prototype thành các phương thức được định nghĩa trong Rails

Page 73: Seminar Ruby

Sử dụng các hàm thư viện 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>

Library and Prototype

Page 74: Seminar Ruby

Sử dụng ajax với thẻ link_to_remote• Tối ưu được cách viết ajax giúp làm cho mã nguồn bớt công

kềnh.

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

Ajax Link

Page 75: Seminar Ruby

Sử dụng ajax với thẻ link_to_function• Dùng để gọi thực thi một hàm 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')" %>

Ajax Link

Page 76: Seminar Ruby

Nội dung giới thiệu

Ajax truyền thống trong Rails JavaScript Libraries and Prototype Form and Ajax Giới thiệu script.aculo.us RJS

Page 77: Seminar Ruby

Muốn gởi dữ liệu lên server thì phải làm sao? sử dụng form

Form non Ajax:

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

Ajax and Form

Page 78: Seminar Ruby

Sử dụng form kết hợp với Ajax

• Form Ajax

• Form normal sử dụng button ajax

Ajax and Form

Page 79: Seminar Ruby

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

Page 80: Seminar Ruby

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

Ajax and Form

Page 81: Seminar Ruby

Nội dung giới thiệu

Ajax truyền thống trong Rails JavaScript Libraries and Prototype Form and Ajax Giới thiệu script.aculo.us RJS

Page 82: Seminar Ruby

Ta sử dụng script.aculo.us để tạo các hiệu ứng và drag-drop

Visual Effect Drag and Drop

Script.aculo.us

Page 83: Seminar Ruby

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

Page 84: Seminar Ruby

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>

Script.aculo.us

Page 85: Seminar Ruby

Nội dung giới thiệu

Ajax truyền thống trong Rails JavaScript Libraries and Prototype Form and Ajax Giới thiệu script.aculo.us RJS

Page 86: Seminar Ruby

Ruby-generated JavaScript Dùng để phát sinh ra mã javascript ở phía server và gửi về lại cho trình duyệt.

#external.rjspage.alert "Hello from an RJS file“

#page.rhtml

<p><%= link_to_remote "Alert with external RJS", :url => { :action => "external" } %></p>

RJS

Page 87: Seminar Ruby

Demo ứng dụng

Page 88: Seminar Ruby

LOGO