顯示具有 Ruby on Rails 標籤的文章。 顯示所有文章
顯示具有 Ruby on Rails 標籤的文章。 顯示所有文章

2010年8月25日 星期三

富model,瘦controller

富model,瘦controller - 李驥平

很久以前看過的一篇文章。挺簡單,不過這種思想很重要。簡單的複述,也不能完全算翻譯。
----先看這麼一段rhtml代碼:渲染模板中加入了這麼多的邏輯,看起來不倫不類,這麼做行是行,但是缺點很多,新手一般有這個毛病。那麼這樣做,首先是可讀性很差,因為在渲染代碼中最好都是貼近HTML代碼,而這堆代碼裡把C的內容也加進來了。
<% people = Person.find( :conditions => ["added_at > ? and deleted = ?", Time.now.utc, false],
:order => "last_name, first_name") %>
<% people.reject { |p| p.address.nil? }.each do |person| %>
">

<%= person.last_name %>, <%= person.first_name %>


<%= (Date.today - person.birthdate) / 365 %>


<% end %>
再看看controller和model裡的東西:
# app/controllers/people_controller.rb
class PeopleController <>
空蕩蕩的controller,而在model裡僅僅有一句關係聲明。這麼組合成的MVC顯得很彆扭,似乎就是一層渲染模板。幾乎把C與M都忽略了。

無論如何這在MVC框架裡是糟糕透頂的現象,MVC經過這麼多年的實踐考驗,它的優點在於「可讀性強」「可維護性好」「模塊化」「關注 點的分離」等等,我想你用MVC框架也就是想實現這些優點哇?那麼首先需要改進的是儘可能的將邏輯內容搬到controller中,controller 的作用就是介於view和model之間,起到一個類似中介的作用。下面來看下這樣改動之後的代碼:

<% @people.each do |person| %>
">

<%= person.last_name %>, <%= person.first_name %>


<%= (Date.today - person.birthdate) / 365 %>


<% end %>
# app/controllers/people_controller.rb
class PeopleController < people =" Person.find(" conditions =""> ["added_at > ? and deleted = ?", Time.now.utc, false],
:order => "last_name, first_name")
@people = @people.reject { |p| p.address.nil? }
end
end
這樣看起來就好多了,模板中的代碼更像是HTML的結構,而且你粗略的看一下controller裡的代碼就能知道在這個action渲染的模板中會顯示什麼數據。
還可以更進一步做的事情就是將現在模板代碼中關於一部分數據的處理挪到Model中來:
# app/models/person.rb
class Person <>

<% @people.each do |person| %>
">
<%= person.name %>
<%= person.age %>

<% end %>
這樣通過在model中添加幾個虛擬屬性,在view裡調用,顯得很合理,而且模板代碼更簡潔明了了。
下一步就是將controller裡的代碼理一理。因為controller只能算是個中介,不應該參與很多的邏輯處理。
# app/models/person.rb
class Person < people =" find(" conditions =""> ["added_at > ? and deleted = ?", Time.now.utc, false],
:order => "last_name, first_name")
people.reject { |p| p.address.nil? }
end

# ...
end

# app/controllers/people_controller.rb
class PeopleController < people =" Person.find_recent">
現在看index這個action,掃一眼就知道它要干嗎。而且如果find_recent方法在以後需要改變時,可以直接在model裡進行修改。
--總結一下,儘量使得controller的actions中的代碼和view中的代碼更少,在action中要是能只寫一行達到效果最好。在view中要儘量使代碼貼近html結構。
還有一個不太明顯的好處就是,瘦action可以使得 respond_to 結構更突出,可以看出輸出的類型是什麼。
class PeopleController < people =" Person.find_recent" xml =""> @people.to_xml(:root => "people") }
format.rss { render :action => "index.rxml" }
end
end
end


2010年6月1日 星期二

rails2.3 routes 新語法

rails2.3 routes筆記 - 逆水行舟

參考鏈接:http://guides.rubyonrails.org/routing.html

多个简单的RESTful的路由可以这样定义:
Ruby代码
收藏代码

map.resources :photos, :books, :videos


以上代码相当于:
Ruby代码
收藏代码

map.resources :photos
map.resources :books
map.resources :videos



单数形式的Resource:
map.resource将生成6个路由规则,与复数形式的resources所不同的是,复数形式多了一个index的action对应的规则,单数形式不需要index,只需要一个show即可。生成的url稍微有所不同,不过和复数形式的resources一样,这些url不用记,有规律,很容易想到该怎么写。

可以通过:controller选项修改RESTful路由默认的controller,比如:
Ruby代码
收藏代码

map.resources :photos, :controller => "images"


本来pohtos的controller是PhotosController,这里变成了ImagesController。

=begin
guides中有这么个用法:
引用
You can also specify a controller namespace with the :namespace option instead of a path:
Ruby代码
收藏代码

map.resources :adminphotos, :namespace => "admin", :controller => "photos"


This can be especially useful when combined with with_options to map multiple namespaced routes together:
Ruby代码
收藏代码

map.with_options(:namespace => "admin") do |admin|
admin.resources :photos, :videos
end


That would give you routing for admin/photos and admin/videos controllers.

可我试了,好像并不是这么回事。
我仿着写了一段:
Ruby代码
收藏代码

map.with_options(:namespace=>'admin') do |admin|
admin.resources :books, :box
end


可我访问/admin/books时Rails却报告No route matches。再试了一下访问/books,却有结果了,结果是:NameError in AdminbooksController#index ——它在原来的BooksController前边加了一个Admin并且把B小写了……
翻了Rails的api也没见着这个:namespace的用法,实在搞不明白。
=end

:singular选项

如果rails不认识某个单词的单数形式,可以通过:singular来设置:
比如有如下routes代码:
Ruby代码
收藏代码

map.resources :teeth


这时候如果在页面上或者Controller里使用tooth_url,Rails会不认识这个tooth——teeth的单数形式,这种情况下就可以加上:singular => "tooth":
Ruby代码
收藏代码

map.resources :teeth, :singular => "tooth"



:as选项
用于修改路由能够识别的url,例如有如下routes代码:
Ruby代码
收藏代码

map.resources :photos, :as => "images"


这时访问/images会被Rails识别,并且调用PhotosController的index方法。但/photos这个URL将不再被Rails识别。

:conditions选项
用于限制能够被识别的请求的HTTP动作,一般不推荐用于RESTful的路由规则中。但可以在map.connect等方法中使用。
用法:
Ruby代码
收藏代码

map.connect 'photo/:id', :controller => 'photos', :action => 'show', :conditions => { :method => :get }



:requirements选项
用于限制url参数的格式,比如:
Ruby代码
收藏代码

map.resources :photos, :requirements => {:id => /[A-Z][A-Z][0-9]+/}


这样,/photos/1将不再被识别,/photos/AB2会被识别。

:path_name选项
用于给自动生成的URL中的'new'和'edit'重命名,但并不改变这两个action的名称,用法:
Ruby代码
收藏代码

map.resources :photos, :path_names => { :new => 'make', :edit => 'change' }


以上,/photos/make仍然调用controller里的new方法。
如果你希望整个rails项目中都使用上面的url,而不是默认的new、edit,可以在enviroment.rb中这样配置:
Ruby代码
收藏代码

config.action_controller.resources_path_names = { :new => 'make', :edit => 'change' }



:only、:except选项
引用
By default, Rails creates routes for all seven of the default actions (index, show, new, create, edit, update, and destroy) for every RESTful route in your application. You can use the : only and :except options to fine-tune this behavior. The : only option specifies that only certain routes should be generated:
Ruby代码
收藏代码

map.resources :photos, :only => [:index, :show]



With this declaration, a GET request to /photos would succeed, but a POST request to /photos (which would ordinarily be routed to the create action) will fail.

The :except option specifies a route or list of routes that should not be generated:
Ruby代码
收藏代码

map.resources :photos, :except => :destroy



In this case, all of the normal routes except the route for destroy (a DELETE request to /photos/id) will be generated.


引用
If your application has many RESTful routes, usingnly and :except to generate only the routes that you actually need can cut down on memory use and speed up the routing process.


:has_one、:has_many 嵌套资源的一种简洁写法:
Ruby代码
收藏代码

map.resources :photos, :has_one => :photographer, :has_many => [:publications, :versions]



2.x的rails开始支持namespace:
Ruby代码
收藏代码

map.namespace(:admin) do |admin|
admin.resources :photos, :has_many => { :tags, :ratings}
end


/admin/photos 将调用Admin::PhotosController的index方法。

:member :collection选项
Ruby代码
收藏代码

map.resources :photos, :member => { :preview => :get }
map.resources :photos, :member => { :prepare => [:get, :post] }
map.resources :photos, :collection => { :search => :get }



GET /photos/1/preview
POST /photos/1/prepare
GET /photos/search

引用
A Note of Caution

If you find yourself adding many extra actions to a RESTful route, it’s time to stop and ask yourself whether you’re disguising the presence of another resource that would be better split off on its own. When the :member and :collection hashes become a dumping-ground, RESTful routes lose the advantage of easy readability that is one of their strongest points.


后面是比较常用的connect的用法,比较熟悉,就不记了。倒是有个with_options第一次见到:
Ruby代码
收藏代码

map.with_options :controller => 'photo' do |photo|
photo.list '', :action => 'index'
photo.delete ':id/delete', :action => 'delete'
photo.edit ':id/edit', :action => 'edit'
end


用于批量设置一组具有某相同选项的路由规则。

rake routes 可以在控制台按顺序输出所有的路由规则。

2010年2月24日 星期三

thin 無法啟動?Missing the Rails 2.3.5 gem?

Thin 是比 Mongrel 更快的Web服务器

安裝 thin 非常簡單
sudo gem install thin

啟動方式
到rails的應用目錄下,打入
thin start

但啟動後卻會出現錯誤訊息
Missing the Rails 2.3.5 gem. Please `gem install -v=2.3.5 rails`, update your RAILS_GEM_VERSION setting in config/environment.rb for the Rails version you do have installed, or comment out RAILS_GEM_VERSION to use the latest version installed.

解決方式:移除rack 1.1.0,保留rack 1.0.1
sudo gem uninstall rack

若沒有 rack 1.0.1,可自行安裝
sudo gem install rack -v 1.0.1

2009年12月30日 星期三

匯入CSV檔 到 Rails SQLite3 資料庫

require 'csv'

#每一行都是的一個按照順序儲存各個欄位的陣列,並且順序跟CSV檔案中的一樣
#匯入myfile.csv,分割符號'|'
CSV.open('myfile.csv', 'r','|') do |row|
# 從 CSV 檔匯入,假設欄位順序為 a, b, c, d
# 為每一欄位建立並儲存一個 Trunk model
Trunk.create!(:a => row[0], :b => row[1], :c => row[2], :d => row[3])
end


其他參考資料ruby-doc.org/CSV

2009年12月29日 星期二

windows ROR 安裝,使用 Mongrel

Mongrel跟Webricks 一樣,是一個方便我們架設 Ruby on Rails 環境的網頁伺服器,但比 Webricks 快速。

安裝
gem install mongrel


使用方式
基本跟 Webrick 差不多。
到想掛載的網頁根目錄,打入
mongrel_rails start

你就會發現網頁已經可以在127.0.0.1:3000打開了。

其他
如果要用 deamon 模式來使用的話
打入

mongrel_rails start -d

即可

如果要使用特定的 port

mongrel_rails start -p 1234

即可

用不同環境啟動

mongrel_rails start -e production/development/test

即可

指定log file

mongrel_rails start -l log/mongrel_log

即可

有啟動的問題

mongrel_rails start -h

即可

重起 Mongrel

mongrel_rails restart


停止 Mongrel

mongrel_rails stop


資料來源:Lighty RoR: Mongrel 使用方式

在Windows上安裝建立 Ruby on Rails 環境

安裝 Ruby and RubyGems

取得最新版本One-Click Ruby Installer, 目前版本為rubyinstaller-1.8.6-p383-rc1.exe。下載後執行, 安裝時勾選「add Ruby excutables to PATH」,然後全部用預設安裝, 此安裝程式會在C:\ruby 安裝Ruby, 且會順便安裝RubyGems。 安裝到最後可以選擇開啟README文件,會顯示剛裝的所有程式的版本。完成安裝後你需要更新gems
gem update --system


安裝 Rails

Rails 非常容易安裝,這要謝謝RubyGems。
在命令提示字元用gem指令來安裝:(執行完指令會停住一段時間,不是當機喔。)
gem install rails


安裝 SQLite(資料庫)

到SQLite Download Page下載 Precompiled Binaries For Windows中兩個檔案

以下是目前最新版本
sqlite-3_6_21.zip A command-line program for accessing and modifying SQLite databases.
sqlitedll-3_6_21.zip This is a DLL of the SQLite library without the TCL bindings.
把裡面的檔案解壓縮到 C:\ruby\bin

執行
gem install sqlite3-ruby

會出現一些 No define for xxxx 的訊息,不用理他。

就此完成!!

預設環境是 Ruby on Rails + SQLite3 +WEBrick

參考資料:在Windows上安裝Ruby on Rails => Rails Wiki

ROR佈署方案 - Nginx + passenger + thin / mongrel

Phusion Passenger/mod_rails令Rails部署变得更容易

Lighty RoR: Passenger :Mod_rails for Apache 終於出世
Phusion Passenger for Nginx - Ruby编程 - JavaEye新闻
一直以來,Lighttp+fastCGI是rails各種部署方式中性能最好的一種,而passenger和前者比較的話,在處理能力上的差距還算可以接受,一直被詬病的是在內存等資源消耗上存在巨大差距.但是隨著passenger2.2.0的發布,在資源消耗方面,Nginx+passenger的方式完全不輸給 Lighttp+fastCGI,而由此提升的性能也會使得passenger和Lighttp+fastCGI之間處理能力更加接近.


由此看來,效能不錯。

可到這邊下載安裝
Install — Phusion Passenger™ (a.k.a. mod_rails / mod_rack)

配合Ruby Enterprise Edition更是厲害。

windows和 Linux下建立 Ruby On Rails 環境 Thin 篇

windows下安裝 Thin A fast and very simple Ruby web server
gem install rack

gem install eventmachine

如果出現
ERROR: could not find gem eventmachine locally or in a repository
請到RubyForge: Ruby/EventMachine: 專案檔案列表下載最新的eventmachine.gem檔案
此處我下載的是eventmachine-0.12.10-x86-mswin32-60.gem

如果下載後存到c:\,請到c:\輸入
gem install eventmachine-0.12.10-x86-mswin32-60.gem


結果最後還是跟我說缺少cl.exe
查詢後才知道,需要安裝visual studio才有內含此檔
然後我又去Downloads visual studio 2008 express

結果下載三次都失敗!!!

弄了一上午,網上也有人說要用 Thin還是在Linux下,Windows無法安裝。
無論如何,我最後決定放棄這個方案了……去他媽的微軟!!!
實在想在WINDOWS下安裝的人可以自行參考這邊
http://groups.google.com/group/mack-framework/browse_thread/thread/767e005a944b1400?pli=1

Ubuntu下安裝Thin,只需要一個步驟就完成!
sudo gem install thin


到你的網頁目錄,啟動
thin start

完成!!

各種Ruby on Rails部署方案 的性能比較表

前後端搭配的測試

各種前端的,我在這裡要測試的性能主要是對於動態請求的響應速度,所以本案中的某些配置既沒有考慮使用Rewrite或其他方式對靜態文件進行單獨處理 (除了Passenger和Swiftiply默認配置便實現了這個功能),也不考慮測試到前端的KeepAlive請求。主要測試以下的組合:
  • Apache + Passenger
  • Nginx + Mongrel
  • Nginx + Evented Mongrel
  • Nginx + Thin
  • Swiftiply + Swiftiplied Mongrel
  • Swiftiply + Thin
  • HAproxy + Mongrel
  • HAproxy + Thin
  • Lighttpd + Mongrel
  • Lighttpd + Thin
  • Lighttpd + FastCGI/Socket
  • Lighttpd + FastCGI/TCP
做服務器的被測試機器為ThinkPad T43,Intel Pentium M 1.86G,1.5G RAM,系統為Ubuntu 8.04。發送請求的是無線局域網中的另外一台筆記本,運行Vista。兩台機器通過TP-Link WR340G+ 801.11g 54MB的無線局域網相連。
前端和後端處於同一台機器上,所有的後端都設為10個進程,綁定於30000-30009端口,Passenger設置為最大生成10個進程,Swiftiply則是綁定於4000端口監聽。FastCGI的socket路徑為/tmp/rails[0-9].sock。


各種部署方式的性能排個名次,以下是後各種方案在並發量>=10的情況下的平均值(去掉出現0值的情況):

前端
後端
平均每秒響應數 最大鏈接限制
Lighttpd
FastCGI/TCP
215.33
64
Lighttpd
FastCGI/Socket
214.65
64
Lighttpd
Thin
196.16
64
Swiftiply
Swiftiplied Mongrel
191.33
N/A
HAproxy
Thin
188.73
10
Swiftiply
Thin(Swiftiplied)
178.96
N/A
Apache2.2/Prefork
Passenger
173.02
N/A
HAproxy
Mongrel
170.4
1
Apache2.2/Worker
Passenger
163.9
N/A
Lighttpd
Mongrel
149.85
64
Nginx
Evented Mongrel
149.78
N/A
Nginx
Thin
143.88
N/A
Nginx
Mongrel
138.86
N/A

在這個表中,Lighttpd的三種方案佔據了前三位,Lighttpd+FastCGI是性能最高的部署方式。這種方式比另一種流行方案Nginx+Mongrel的方式性能提升了高達50%!
FastCGI的好處在此體現出來:
  • 二進制協議,無需HTTP的解析
  • 與前端可以建立持久鏈接
  • 沒有鎖和上下文切換的開銷
另外Lighttpd相對於Nginx的優勢在於請求和響應的接收緩衝區很大,省去多次接收和發送的開銷。
Lighttpd+Thin的方式的性能列第三位,這點似乎出乎意料之外,但實際上是因為Lighttpd 1.5支持對HTTP後端建立HTTP KeepAlive鏈接。在第一部分對後端單獨的測試中,小並發下的Thin的KeepAlive測試性能並不比FastCGI差,同時Thin實現了非 阻塞IO,而FastCGI則是阻塞式的。相反,HAproxy和Nginx則都不支持HTTP KeepAlive。
而Swiftiply的方式也顯示出了強勁的性能,應該是得益於它的「讓後端主動連接到Swiftiply」的這種特殊的結構。
當前備受關注的Passenger的部署方式在本案中並沒有顯示出特別的性能上的優勢,不過如果將並發鏈接數放在300以內,則 Apache2.2/Prefork + Passenger的部署方式的平均每秒響應數上升為204.03,這樣看來,倘若為Apache進行一些優化配置,依然不失為一種高效的部署方案。而同 時Passenger又是最容易配置的一種方案,能達到這種效果已經非常令人滿意。
HAproxy + Mongrel並限制鏈接數為1,則是一種穩定、保守的部署方式,雖然在這裡性能不出眾,但是穩定性非常好。
最後,與Nginx相關的三種方案都排在了該榜的末尾,由於Nginx的反向代理負載均衡缺少一些高級的特性以及Rails本身的特性而導致其不適合單獨應用在Rails程序的部署上:
  • 缺少到後台服務器端的鏈接數限制的能力,這導致了Mongrel在接受大量請求時將時間消耗在上下文切換和鎖的爭用上。
  • 缺乏建立到後台服務器端的持久鏈接的能力,這導致了在鏈接的打開、建立、關閉上花費了額外的開銷。
更詳細的分析過程和資料請看浅析Ruby on Rails部署方案