seminar ruby
TRANSCRIPT
LOGO
Ruby On RailsRuby On Rails
Nhóm trình bày: NewWindKhoa CNTT - ĐHKHTN
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
1. Tổng quan về Ruby On Rails
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
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
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
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
Rails là: Web-application framework. Được viết bởi David Heinemeier Hansson. Mã nguồn mở
Tổng quan về Rails
Tổng quan về Rails
David Heinemeier Hansson
Sinh ngày: 15 - 10 – 1979 Quốc tịch: Mỹ Nghề nghiệp: programmer
Tổng quan về Ruby On Rails
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ả
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
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 %>
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 %>
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 %>
Tổng quan về Ruby
Operator
Số học: +, -, *, /, %, … So sánh: ==, !=, >, >=, <, <=, … Gán: =, +=, … Logic: &&, ||, !, …
Giống C#Giống C#
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 %>
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 %>
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
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();
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 %>
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
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
2. Ruby On Rails, lập trình với CSDL
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
Giới thiệu về kiến trúc MVC
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
Ứ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
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
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
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
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.
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
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
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
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
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>
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
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ì?
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
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
Demo
Tóm lại quá trinh này thực hiện như sau:
new
new.html
create
Controller
View
Model
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ị
3. Quản lý session, cookies, mail
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]
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]
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
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"
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
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
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
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
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
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
Send and Receive Email
Demo
4. Scaffolding, Plugins
Scaffolding
Tự động phát sinh code cho Model, View, Controller
Demo
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)
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)
Acts_as_authenticated
class ApplicationController < ActionController::Base
include AuthenticatedSystem ...end
class Admin::BaseController < ApplicationController
before_filter :login_requiredend
class Admin::AuthorController < Admin::BaseController
...end
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
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 %>
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)
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
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) %>
5. Ajax On Rails
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
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
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
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
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
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
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
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
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
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
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
Sử dụng form kết hợp với Ajax
• Form Ajax
• Form normal sử dụng 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 %>
Ajax and Form
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
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
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>
Script.aculo.us
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
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
Demo ứng dụng
LOGO