亚洲中文字幕一二三四区,亚洲色无码专区一区,久久亚洲精品成人无码网站 http://www.tkk7.com/chengang/category/20990.html    逝者如斯夫不舍晝夜zh-cnTue, 06 Nov 2007 15:40:49 GMTTue, 06 Nov 2007 15:40:49 GMT60VIM的常用插件+配置文件+資料http://www.tkk7.com/chengang/archive/2007/10/18/153970.html陳剛陳剛Thu, 18 Oct 2007 10:15:00 GMThttp://www.tkk7.com/chengang/archive/2007/10/18/153970.htmlhttp://www.tkk7.com/chengang/comments/153970.htmlhttp://www.tkk7.com/chengang/archive/2007/10/18/153970.html#Feedback6http://www.tkk7.com/chengang/comments/commentRss/153970.htmlhttp://www.tkk7.com/chengang/services/trackbacks/153970.html 我把VIM的常用插件,自己用的配置文件,收羅的一些資料一并打包了,省得初用VIM的人找來找去浪費時間。

http://www.tkk7.com/Files/chengang/myvim.zip



在ubuntu7.10中的gvim出現亂碼,這時需要在主目錄下的“.vimrc”文件中加上定義字體的一句。我用的是“微軟雅黑”字體所以此句為:
set?guifont=YaHei\?Consolas\?Hybrid\?10
注意:字體名中有空格的,用斜杠分開,而且斜杠后面一定要有一個空格。10是字體大小,前面有一個空格。


陳剛 2007-10-18 18:15 發表評論
]]>
個性化頁面布局的設計思考與Rails初步實現http://www.tkk7.com/chengang/archive/2007/10/11/151900.html陳剛陳剛Wed, 10 Oct 2007 16:00:00 GMThttp://www.tkk7.com/chengang/archive/2007/10/11/151900.htmlhttp://www.tkk7.com/chengang/comments/151900.htmlhttp://www.tkk7.com/chengang/archive/2007/10/11/151900.html#Feedback0http://www.tkk7.com/chengang/comments/commentRss/151900.htmlhttp://www.tkk7.com/chengang/services/trackbacks/151900.html
這個設計其實很簡單,就是“引擎+配置“--主體頁面只定義一個rthml,可以把它看做頁面引擎,然后用一個配置文件指定了頁面所應具有的模塊和數據。 頁面模塊就象一個個裝有數據的盒子,通過“頁面引擎 + 配置文件”把這些盒子組合起來,象搭積木一樣。頁面引擎是各用戶共用的,配置文件是各用戶獨有的,這樣一裝配起來,就形成了用戶的個性化頁面。

剩下的重點就是怎么定義配置文件。首先是要劃清配置文件的責任界線----它只負責定義盒子里的數據,還有盒子的嵌套關系,而大小和位置等布局方面則全部交給CSS去負責。

上面是初步想法,下面看看具體實現,代碼僅供參考

以下是某個用戶的配置文件(我沒用XML,而是用YAML)。board_1是指ID=1這個欄目所用的配置定義。topContent是一個
<div>的id值,我把每個欄目的頁面分成topContent頂、sideContent邊(左或右由CSS決定)、primaryContent 主要、bottomContent底。topic是指添加一個模塊(盒子),顯示一個主題內容。和topic類似是還有顯示圖像的image、顯示主題列 表的topics、顯示分類列表的categories等等等等。它們各有不同的屬性值,比如topic模塊,它需要定指它的主題id,以及它所用的 view(topics/_show_hot.rhtml? or? topics/_show.rhtml等等)。

(雖然這個配置文件抽象得還不夠,但這樣子已經可以解決我的需要了,那
暫時這樣先了。)

template.yml
?
  1. board_2:??
  2. ??
  3. board_1:??
  4. -?topContent:??
  5. ??-?topic:??
  6. ??????topic_id:?7??
  7. ??????view:?topics/show_hot??
  8. -?sideContent:??
  9. ??-?image:??
  10. ??????url:?/images/news.jpg??
  11. ??-?categories:??
  12. ??????board:?5??
  13. ??????view:?tree??
  14. ??-?topics:??
  15. ??????board:?5??
  16. ??????per_page:?4??
  17. ??????view:?index_simple??
  18. ??-?topics:??
  19. ??????board:?6??
  20. -?primaryContent:??
  21. ??-?topics:??
  22. ??????board:?4??
  23. ??????view:?index??
  24. ??-?topic:??
  25. ??????topic_id:?7??
  26. ??????view:?util/box??
  27. ??
  28. board_3:??

然后在controller里把配置文件讀入,再轉化成模型類。我把各個界面模塊看做一個個盒子Box
這是它的頂級Box
ruby 代碼
?
  1. class?Box??
  2. ??attr_accessor?:html_id,?:view,?:boxes??
  3. ??def?initialize
  4. ????@boxes=[]??
  5. ??end??
  6. end??

這是topic模塊的
ruby 代碼
?
  1. class?TopicBox?<?Box??
  2. ??attr_accessor?:topic_id??
  3. end??

這是Image模塊的
ruby 代碼
?
  1. class?ImageBox?<?Box??
  2. ??attr_accessor?:url??
  3. end????

.....等 等, 其他的Box子類大同小異

然后在一個controller里把這些配置信息轉成Box模型類
ruby 代碼
?
  1. templates?=? YAML::load(File.read("public/uploads/#{user_id}/config/template.yml"))
  2. template?=?templates.find{|o|?o[0]=="board_#{@board.id}"?}??
  3. args?=?template[1]??
  4. ??
  5. @boxes?=?[]??
  6. args.each?do?|arg1_hash|??
  7. ??arg1_hash.each?do?|key1,?value1|??
  8. ????board_box?=?BoardBox.new??
  9. ????board_box.html_id?=?key1??
  10. ????@boxes?<<?board_box??
  11. ????value1.each?do?|arg2_hash|??
  12. ??????arg2_hash.each?do?|key2,?value2|??
  13. ????????case?key2??
  14. ????????when?'topics'??
  15. ??????????box?=?TopicsBox.new??
  16. ??????????box.board_id?=?value2['board']??
  17. ??????????box.per_page?=?value2['per_page']||2??
  18. ??????????box.view?=?value2['view']||'index_simple'??
  19. ??????????board_box.boxes?<<?box???
  20. ????????when?'categories'??
  21. ??????????box?=?CategoriesBox.new??
  22. ??????????box.board_id?=?value2['board']??
  23. ??????????box.view?=?value2['view']||'list'??
  24. ??????????board_box.boxes?<<?box???
  25. ????????when?'image'??
  26. ??????????box?=?ImageBox.new??
  27. ??????????box.url?=?value2['url']??
  28. ??????????board_box.boxes?<<?box???
  29. ????????when?'topic'??
  30. ??????????box?=?TopicBox.new??
  31. ??????????box.topic_id?=?value2['topic_id']??
  32. ??????????box.view?=?value2['view']||'util/box'??
  33. ??????????board_box.boxes?<<?box???
  34. ????????end??
  35. ??????end??
  36. ????end??
  37. ??end??
  38. end?

最后是它頁面引擎(邏輯代碼和頁面代碼混在一起,比較丑陋)
ruby 代碼
?
  1. <%?@boxes.each?do?|box1|?%>??
  2. "<%=box1.html_id%>">??/span>
  3. ??<%?box1.boxes.each?do?|box2|??
  4. ???????p1?box2.class.to_s??
  5. ??
  6. ??????case?box2.class.to_s??
  7. ??????when?'TopicsBox'??
  8. ????????board_id?=?box2.board_id??
  9. ????????if?board_id??
  10. ??????????board?=?Board.find(board_id)??
  11. ??????????topics?=?Topic.by_board_id(board_id,?:per_page?=>?box2.per_page)???
  12. ??????????%>??
  13. ??????????<%=?render(:partial?=>?"topics/#{box2.view}",?:locals?=>?{:title?=>board.title,?:topics?=>?topics?})%>??
  14. ????????<%end??
  15. ??????when?'CategoriesBox'??
  16. ????????board_id?=?box2.board_id??
  17. ????????if?board_id??
  18. ??????????board?=?Board.find(board_id)??
  19. ??????????categories?=?board.categories??
  20. ??????????%>??
  21. ??????????<%=?render?:partial?=>?"categories/#{box2.view}",?:locals?=>?{:board?=>board,?:categories?=>?categories?}?%>??
  22. ????????<%end%>??
  23. ??????<%when?'ImageBox'%>??
  24. ????????<%=?box_tag?:header=>false%>??
  25. ??????????<%=image_tag(box2.url,?:border?=>?0)?%>??
  26. ????????<%=?end_box_tag?%>??
  27. ??????<%when?'TopicBox'??
  28. ????????topic?=?Topic.find(box2.topic_id)?%>??
  29. ????????<%=render(:partial?=>?"#{box2.view}",?:locals?=>?{:title?=>topic.title,?:content?=>?topic.content,?:topic?=>?topic?})%>??
  30. ??????<%end??
  31. ??end%>?
?

這樣,以后想在頁面上增加刪除什么模塊,修改配置文件就行了。當然給用戶用,還必須得用AJAX來寫個GUI界面,總不能讓用戶手工去改配置文件吧。


陳剛 2007-10-11 00:00 發表評論
]]>
抽取FCKEditor的瀏覽圖片功能http://www.tkk7.com/chengang/archive/2007/09/26/148412.html陳剛陳剛Wed, 26 Sep 2007 10:49:00 GMThttp://www.tkk7.com/chengang/archive/2007/09/26/148412.htmlhttp://www.tkk7.com/chengang/comments/148412.htmlhttp://www.tkk7.com/chengang/archive/2007/09/26/148412.html#Feedback0http://www.tkk7.com/chengang/comments/commentRss/148412.htmlhttp://www.tkk7.com/chengang/services/trackbacks/148412.html
文/陳剛 www.chengang.com.cn 轉載請保留出處
在閱讀FCKEditor的源碼之后,做如下處理。

1. 新增兩個javascript函數。
var?currentImageTextID;

//FCKEditor的文件瀏覽窗關閉后,會調用此函數,并把所選圖片的url傳入。
function?SetUrl(url){
??document.getElementById(currentImageTextID).value
=url;
}

//imageTextID:?圖片文本框的ID值
//
uploadPath:?服務器的圖片目錄
//
type:?瀏覽類型,值可為Image/Flash/File/Media,如果為空字串,則表示瀏覽所有類型的文件
function?OpenImageBrowser(imageTextID,?uploadPath,?type?)?{
??currentImageTextID?
=?imageTextID;
??window.open('
/javascripts/fckeditor/editor/filemanager/browser/default/browser.html?uploaded='+uploadPath +'&Type='+type+'&Connector=/fckeditor/command','Browse/Upload?Images','toolbar=no,status=no, resizable=yes,dependent=yes, scrollbars=yes,width=600,height=400')
}

2.在View中這樣使用
標志圖片:
<
input?id="topic_image"?name="topic[image]"?size="30"?type="text">
<
input?value="瀏覽服務器"?onclick="OpenImageBrowser('topic_image',?'/uploads/s<%= params[:user_id]%>',?'Image')"?type="button">




陳剛 2007-09-26 18:49 發表評論
]]>
讓Rails版的FCKEditor支持動態設置上傳目錄http://www.tkk7.com/chengang/archive/2007/09/26/148114.html陳剛陳剛Wed, 26 Sep 2007 02:13:00 GMThttp://www.tkk7.com/chengang/archive/2007/09/26/148114.htmlhttp://www.tkk7.com/chengang/comments/148114.htmlhttp://www.tkk7.com/chengang/archive/2007/09/26/148114.html#Feedback3http://www.tkk7.com/chengang/comments/commentRss/148114.htmlhttp://www.tkk7.com/chengang/services/trackbacks/148114.html
文/陳剛 www.chengang.com.cn 轉載請保留出處
1.修改fckeditor_controller.rb,把它那幾個private方法修改如下:
??
??
private
??def?current_directory_path
????base_dir?
=?"#{RAILS_ROOT}/public"

????#TODO?在創建用戶時,就建立好目錄。這時可以去掉這部份代碼,提高運行效率。
????(
"#{params[:uploaded]||UPLOADED}/#{params[:Type]}").split('/').each?do?|s|
????next?
if?s==''
????????base_dir?
+=?'/'?+?s
????????Dir.mkdir(base_dir,
0775)?unless?File.exists?(base_dir)
????end
????
????check_path(
"#{base_dir}#{params[:CurrentFolder]}")
??end
??
??def?upload_directory_path
????uploaded?
=?@request.relative_url_root.to_s+"#{params[:uploaded]||UPLOADED}/#{params[:Type]}"
????
"#{uploaded}#{params[:CurrentFolder]}"
??end
??
??def?check_file(file)
????#?check?that?the?file?is?a?tempfile?object
????unless?
"#{file.class}"?==?"Tempfile"?||?"#{file.class}"?==?"StringIO"
??????@errorNumber?
=?403
??????
throw?Exception.new
????end
????file
??end
??
??def?check_path(path)
????exp_path?
=?File.expand_path?path
????
if?exp_path?!~?%r[^#{File.expand_path(RAILS_ROOT)}/public#{params[:uploaded]||UPLOADED}]
??????@errorNumber?
=?403
??????
throw?Exception.new
????end
????path
??end

另外,它前面的常量UPLOADED_ROOT也沒用了,可以刪掉。


2. 在上面的代碼中params[:uploaded]是關鍵,它就是我們動態定義的上傳目錄。該值來自于FCKEditor的一些html頁面,它是通過get參數傳入的。修改browser.html文件(如下粗體部份),在它的url請求中把我們定義目錄加入到get參數列中,這樣它就可以傳到fckeditor_controller.rb里了


var?sServerPath?
=?GetUrlParam(?'ServerPath'?)?;
if?(?sServerPath.length?>?0?)
????oConnector.ConnectorUrl?
+=?'ServerPath='?+?escape(?sServerPath?)?+?'&'?;

var?sUploaded?
=?GetUrlParam(?'uploaded'?)?;
if?(?sUploaded.length?>?0?)
????oConnector.ConnectorUrl?
+=?'uploaded='?+?escape(?sUploaded?)?+?'&'
?;

oConnector.ResourceType????????
=?GetUrlParam(?'Type'?)?;
oConnector.ShowAllTypes????????
=?(?oConnector.ResourceType.length?==?0?)?;


3.? 上面
的GetUrlParam(?'uploaded'?) 的值來自于fckcustom.js。修改fckcustom.js(如下粗體部份),把uploaded加入到get參數列中。

//?CHANGE?FOR?APPS?HOSTED?IN?SUBDIRECTORY
FCKRelativePath?
=?'';

//?DON'T?CHANGE?THESE
FCKConfig.LinkBrowserURL?=?FCKConfig.BasePath?+?'filemanager/browser/default/browser.html?Connector='+FCKRelativePath+'/fckeditor/command';
FCKConfig.ImageBrowserURL?
=?FCKConfig.BasePath?+?'filemanager/browser/default/browser.html?uploaded='+FCKConfig.uploaded+'&Type=Image&Connector='+FCKRelativePath+'/fckeditor/command';
FCKConfig.FlashBrowserURL?
=?FCKConfig.BasePath?+?'filemanager/browser/default/browser.html?uploaded='+FCKConfig.uploaded+'&Type=Flash&Connector='+FCKRelativePath+'/fckeditor/command';

FCKConfig.LinkUploadURL?
=?FCKRelativePath+'/fckeditor/upload';
FCKConfig.ImageUploadURL?
=?FCKRelativePath+'/fckeditor/upload?Type=Image&uploaded='+FCKConfig.uploaded;
FCKConfig.FlashUploadURL?
=?FCKRelativePath+'/fckeditor/upload?Type=Flash&uploaded='+FCKConfig.uploaded;
FCKConfig.AllowQueryStringDebug?
=?false;
FCKConfig.SpellChecker?
=?'SpellerPages';

//?ONLY?CHANGE?BELOW?HERE
FCKConfig.SkinPath?
=?FCKConfig.BasePath?+?'skins/silver/';
FCKConfig.AutoDetectLanguage?
=?false?;
FCKConfig.DefaultLanguage?
=?'zh-cn'?;
FCKConfig.FontNames?
=?'微軟雅黑;宋體;黑體;隸書;楷體_GB2312;Arial;Comic?Sans?MS;Courier?New;Tahoma;Times?New?Roman;Verdana'?;

FCKConfig.ToolbarSets[
"Simple"]?=?[
????[
'Source','-','FitWindow','Preview','-','Templates'],
????[
'PasteText','PasteWord'],
????[
'Undo','Redo','Find','Replace'],
????
'/',
????[
'RemoveFormat','Bold','Italic','Underline','StrikeThrough'],
????[
'OrderedList','UnorderedList','Outdent','Indent'],
????[
'JustifyLeft','JustifyCenter','JustifyRight','JustifyFull'],
????????[
'TextColor','BGColor'],
????[
'Link','Unlink','Anchor'],
????[
'Image','Flash','Table','Rule','Smiley'],
????
'/',
????[
'Style','FontFormat','FontName','FontSize']
]?;

4. 上面FCKConfig.uploaded的值來自于fckeditor.rb。在fckeditor.rb中加入一句(如下粗體所示)。
??????javascript_tag(?"var?oFCKeditor?=?new?FCKeditor('#{id}',?'#{width}',?'#{height}',?'#{toolbarSet}');\n"+
??????????????????????
"oFCKeditor.BasePath?=?\"#{base_path}\"\n"+
??????????????????????"oFCKeditor.Config['CustomConfigurationsPath']?=?'../../fckcustom.js';\n"+
??????????????????????
"oFCKeditor.Config['uploaded']?=?'#{options[:path]}';\n"+
??????????????????????
"oFCKeditor.ReplaceTextarea();\n")?????????????????????????

5.不過上面oFCKeditor.Config['uploaded']的值要傳到fckcustom.js的FCKConfig.uploaded里,還需要修改fckeditorcode_gecko.js和fckeditorcode_ie.js(這兩個文件對javascript進行了壓縮處理,修改起來較難操作)。我是參考了oFCKeditor.Config['CustomConfigurationsPath'] 這個參數的載入實現,才找到這種鳥不生蛋的地方。搜索這兩個文件的關鍵字CustomConfigurationsPath,找到如下一行,然后加入一個else if判斷(如下粗體所示)。
if?(D=='CustomConfigurationsPath')?FCKConfig[D]=E;else?if?(D=='uploaded')?FCKConfig[D]=E;else?if?(E.toLowerCase()=="true")?this.PageConfig[D]=true;


6.最后在fckeditor.rb里的#{options[:path]}來自于我們前臺的view了。如下粗體所示,把標準的fckeditor_textarea新增加了一個參數,其中params[:user_id]是把用戶的ID值做為目錄名。這樣就實現了動態改變FCKEditor的上傳目錄。

<%=fckeditor_textarea(:topic,?:content,?:ajax?=>?true,?:toolbarSet?=>?'Simple',?:height?=>?'400px',? :path?=>?"/uploads/#{params[:user_id]}")?%>


修改完后需要重啟WEB服務,最后別忘記把public/javascripts/fckeditor和vendor/plugins/fckeditor/public/javascripts同步一下,原因見http://www.tkk7.com/chengang/archive/2007/09/24/147867.html


陳剛 2007-09-26 10:13 發表評論
]]>
定制FCKEditor,以及使其中文化http://www.tkk7.com/chengang/archive/2007/09/24/147867.html陳剛陳剛Mon, 24 Sep 2007 10:24:00 GMThttp://www.tkk7.com/chengang/archive/2007/09/24/147867.htmlhttp://www.tkk7.com/chengang/comments/147867.htmlhttp://www.tkk7.com/chengang/archive/2007/09/24/147867.html#Feedback0http://www.tkk7.com/chengang/comments/commentRss/147867.htmlhttp://www.tkk7.com/chengang/services/trackbacks/147867.html
文/陳剛? www.chengang.com.cn
首先,我們來看看FCKEditor在Rails中的運行特性,其插件主要是安裝在vendor/plugins/fckeditor。主要的代碼在vendor/plugins/fckeditor/public/javascripts,其中fckcustom.js是配置文件,另外更深一層的子目錄fckeditor中還有一個fckconfig.js也是配置文件。fckcustom.js配置的優先順序大于fckconfig.js,因此一般修改fckcustom.js就可以了,不必去動fckconfig.js。

在啟動WEBrick( ruby script/server)時,會自動把vendor/plugins/fckeditor/public/javascripts的內容復制到public/javascripts目錄。因此如果你修改了FCKEditor的配置文件之后,需要把復制到public/javascripts目錄的FCKEditor相關文件刪除掉,然后再重啟WEBrick。當然,你也可以直接修改public/javascripts目錄的FCKEditor的緩存的配置文件,這樣不必重啟WEBrick,就可以立即看到修改效果。不過建議你在完成修改后,同時也要更新vendor/plugins/fckeditor/public/javascripts下的配置文件,畢竟public/javascripts里的應該算是臨時文件。


1.中文化

在fckcustom.js里加入兩項(粗體顯示)
FCKConfig.SkinPath?=?FCKConfig.BasePath?+?'skins/silver/';
FCKConfig
.AutoDetectLanguage?=?false?;
FCKConfig
.DefaultLanguage?=?'zh-cn'
?;

2. 定制FCKEditor的工具欄
修改fckcustom.js里的如下項目,增刪改自便。
FCKConfig.ToolbarSets["Simple"]?=?[?? 。。。 。。。

這里要注意一點,有些網上文章把:toolbarSet寫成了:toolbarKit,這是錯誤的。如果你發現對工具欄的配置不起作用,那么要檢查一下。正確的寫法如下:
<%=fckeditor_textarea(:topic,?:content,?:ajax?=>?true,?:toolbarSet?=>?'Simple',?:width?=>?'100%',?:height?=>?'300px')?%>








陳剛 2007-09-24 18:24 發表評論
]]>
error_messages_for的中文化http://www.tkk7.com/chengang/archive/2007/09/19/146548.html陳剛陳剛Wed, 19 Sep 2007 09:35:00 GMThttp://www.tkk7.com/chengang/archive/2007/09/19/146548.htmlhttp://www.tkk7.com/chengang/comments/146548.htmlhttp://www.tkk7.com/chengang/archive/2007/09/19/146548.html#Feedback0http://www.tkk7.com/chengang/comments/commentRss/146548.htmlhttp://www.tkk7.com/chengang/services/trackbacks/146548.htmlApplicationHelper
文/陳剛? www.chengang.com.cn? 轉載請聲明出處

? def?error_messages_for(*params)
????
#add?by?glchengang
????key_hash?=?{}
????
if?params.first.is_a?(Hash)
??????key_hash?
=??params.first
??????params
.delete_at(0)
????end
????
#add?end

????options?
=?params.last.is_a?(Hash)???params.pop.symbolize_keys?:?{}
????objects?
=?params.collect?{|object_name|?instance_variable_get("@#{object_name}")?}.compact
????count???
=?objects.inject(0)?{|sum,?object|?sum?+?object.errors.count?}
????
unless?count.zero?
??????html?
=?{}
??????[
:id,?:class].each?do?|key|
????????
if?options.include?(key)
??????????value?
=?options[key]
??????????html[key]?
=?value?unless?value.blank?
????????
else
??????????html[key]?
=?'errorExplanation'
????????end
??????end
??????
#?change?by?glchengang
??????header_message?=?"有#{count}個錯誤"
#???????header_message?=?"#{pluralize(count,?'error')}?prohibited?this?#{(options[:object_name]?||?params.first).to_s.gsub('_',?'?')}?from?being?saved"
??????
??????#add?by?glchengang

??????error_messages?=?objects.map?do?|object|
????????temp?
=?[]
????????object
.errors.each?do?|attr,?msg|
??????????temp?
<<?content_tag(:li,?(key_hash[attr]?||?attr)?+?msg)?
????????end
????????temp
??????end
??????
#add?end

#????????error_messages?=?objects.map?{|object|?object.errors.full_messages.map?{|msg|?content_tag(:li,?msg)?}?}

??????content_tag(:div,
????????content_tag(options[
:header_tag]?||?:h2,?header_message)?<<
#???????????content_tag(:p,?'There?were?problems?with?the?following?fields:')?<<
??????????content_tag(:ul,?error_messages),
????????html
??????)
????
else
??????
''
????end
??end


使用依然兼容老的方式,你也可以傳入一個哈希表,把模型字段顯示成對應的中文,示例如下:
<%=?
h?
=?{'username'=>'用戶名',?'password'=>'密碼'}
error_messages_for?h
,?:user
%>

另外,還要在environment.rb的最后插入以下代碼:

errors?=?ActiveRecord::Errors.default_error_messages
errors[
:taken]?=?'已經被使用'
errors[
:blank]?=?'不能為空'



陳剛 2007-09-19 17:35 發表評論
]]>
讓will_paginate的分頁支持ajaxhttp://www.tkk7.com/chengang/archive/2007/09/02/142077.html陳剛陳剛Sun, 02 Sep 2007 07:42:00 GMThttp://www.tkk7.com/chengang/archive/2007/09/02/142077.htmlhttp://www.tkk7.com/chengang/comments/142077.htmlhttp://www.tkk7.com/chengang/archive/2007/09/02/142077.html#Feedback7http://www.tkk7.com/chengang/comments/commentRss/142077.htmlhttp://www.tkk7.com/chengang/services/trackbacks/142077.html
文/陳剛 (www.chengang.com.cn)
但一直搜不到它支持ajax分面的方法 ,于是我參考它分頁方法的源代碼(位于:vendor/plugins/will_paginate/lib/will_paginate/view_helpers.rb),稍微改寫,變成了一個支持ajax的分頁方法。以下代碼復制到application_helper里即可。


??
#-----------------------------------------
??#?will_paginate插件的ajax分頁
??#-----------------------------------------
??@@pagination_options?=?{?:class?=>?'pagination',
????????
:prev_label???=>?'上一頁',
????????
:next_label???=>?'下一頁',
????????
:inner_window?=>?4,?#?links?around?the?current?page
????????:outer_window?=>?1,?#?links?around?beginning?and?end
????????:separator????=>?'?',?#?single?space?is?friendly?to?spiders?and?non-graphic?browsers
????????:param_name???=>?:page,
????????
#add?by?chengang
????????:update?=>nil,?#ajax所要更新的html元素的id
????????:url_suffix?=>?''??#url的后綴,主要是為了補全REST所需要的url
????????#add?end
????????}
??mattr_reader?
:pagination_options

??def?will_paginate_remote(entries?
=?@entries,?options?=?{})
????total_pages?
=?entries.page_count

????
if?total_pages?>?1
??????options?
=?options.symbolize_keys.reverse_merge(pagination_options)
??????page
,?param?=?entries.current_page,?options.delete(:param_name)
??????
??????inner_window
,?outer_window?=?options.delete(:inner_window).to_i,?options.delete(:outer_window).to_i
??????
#add?by?chengang
??????update?=??options.delete(:update)
??????suffix?
=??options.delete(:url_suffix)
??????url?
=?request.env['PATH_INFO']?
??????url?
+=?suffix?if?suffix
??????
#add?end

??????
min?=?page?-?inner_window
??????
max?=?page?+?inner_window
??????
if?max?>?total_pages?then?min?-=?max?-?total_pages
??????elsif?
min?<?1??then?max?+=?1?-?min
??????
end
??????
??????
current???=?min..max
??????beginning?
=?1..(1?+?outer_window)
??????tail??????
=?(total_pages?-?outer_window)..total_pages
??????visible???
=?[beginning,?current,?tail].map(&:to_a).flatten.sort.uniq
??????links
,?prev?=?[],?0

??????visible
.each?do?|n|
????????
next?if?n?<?1
????????
break?if?n?>?total_pages

????????unless?n?
-?prev?>?1
??????????
prev?=?n
??????????
#change?by?chengang
??????????text?=?(n==page???n?:?"[#{n}]")
??????????links?
<<?page_link_remote_or_span((n?!=?page???n?:?nil),?'current',?text,?param,?update,?url)
????????
else
??????????
prev?=?n?-?1
??????????links?
<<?''
??????????redo
????????
end
??????
end
??????
??????
#change?by?chengang
??????links.unshift?page_link_remote_or_span(entries.previous_page,?'disabled',?options.delete(:prev_label),?param,?update,?url)
??????links
.push????page_link_remote_or_span(entries.next_page,?????'disabled',?options.delete(:next_label),?param,?update,?url)
??????
#change?end

??????content_tag?
:div,?links.join(options.delete(:separator)),?options
????
end
??
end
??
protected

??def?page_link_remote_or_span(page
,?span_class,?text,?param,?update,?url)
????unless?page
??????content_tag?
:span,?text,?:class?=>?span_class
????
else
??????link_to_remote?text
,?:update?=>?update,?:url?=>?"#{url}?#{param.to_sym}=#{page}",?:method=>:get
????
end
??
end


在view中的使用如下所示:
??????????<%=will_paginate_remote?@topics,?:update?=>?'topicList',?:url_suffix?=>?url_suffix%>




陳剛 2007-09-02 15:42 發表評論
]]>
在Rails中使用FCKeditor插件實現WEB富文本編輯http://www.tkk7.com/chengang/archive/2007/08/25/139287.html陳剛陳剛Sat, 25 Aug 2007 08:44:00 GMThttp://www.tkk7.com/chengang/archive/2007/08/25/139287.htmlhttp://www.tkk7.com/chengang/comments/139287.htmlhttp://www.tkk7.com/chengang/archive/2007/08/25/139287.html#Feedback0http://www.tkk7.com/chengang/comments/commentRss/139287.htmlhttp://www.tkk7.com/chengang/services/trackbacks/139287.html
文/陳剛? (www.chengang.com.cn)

環境:ubuntu linux 7.0.4? +? ruby 1.8.5 + Rails 1.2.3 + FCKeditor 0.4.1

直接從它的subversion庫里取得該Rails插件。先進入到你的項目根目錄,再執行如下命令
ruby?script/plugin?install?svn://rubyforge.org/var/svn/fckeditorp/trunk/fckeditor

其他說明:
(1)你的linux必須先安裝了subversion。(ubuntu里用新立得搜subversion即得)
(2)把命令中的install 改為 destory,可以刪除安裝。
(3)我取到的是2007年4月份最后更新的, v 0.4.1版
(4)FCKeditor安裝在項目根目錄下的vendor/plugins/fckeditor 里,
(5)vendor/plugins/fckeditor里的README很值得一讀,我碰到Ajax問題,查了所以網上的中文資料都沒有提到,在這個README卻有。


用如下語句在頁面里含入它的javascript庫
<%=?javascript_include_tag?:fckeditor?%>??

<%=?javascript_include_tag?"fckeditor/fckeditor"?%>


在需要富文本的Form表單用如下語句生成一個富文件編輯框:
<%=?fckeditor_textarea("topic",?"content",?:toolbarSet?=>?'Simple',?:width?=>?'100%',?:height?=>?'200px')?%>

說明:topic對應模型對象,content對應它的字段。也就是要求當前頁要有@topic這個實例變量。


如果是用了ajax,則需要在form_remote_tag加上一個before項
??<%=?form_remote_tag(:update?=>?update,
??????????????????????:before?
=>?fckeditor_before_js('topic',?'content'),
??????????????????????:url?
=>?{:controller?=>?'topics',?:action?=>?'create',?:template?=>?'show'}?)%>

并且富文件編輯框要加一個ajax=true的選項:
<%=?fckeditor_textarea(:topic,?:content,?:ajax?=>?true,?:toolbarKit?=>?'Simple',?:width?=>?'100%',?:height?=>?'600px')?%>





在使上傳圖片的功能時碰到了錯誤。彈出出alert對話框,顯示:Error on file upload.Error number: 403

在日志里顯示如下,表面上看好象是路由配置的問題

ActionController::RoutingError (no route found to match "/fckblank.html" with {:method=>:get}):
/var/lib/gems/1.8/gems/actionpack-1.13.3/lib/action_controller/routing.rb:1292:in `recognize_path'
/var/lib/gems/1.8/gems/actionpack-1.13.3/lib/action_controller/routing.rb:1282:in `recognize'
/var/lib/gems/1.8/gems/rails-1.2.3/lib/dispatcher.rb:40:in `dispatch'
/var/lib/gems/1.8/gems/rails-1.2.3/lib/webrick_server.rb:113:in `handle_dispatch'
/var/lib/gems/1.8/gems/rails-1.2.3/lib/webrick_server.rb:79:in `service'
/usr/lib/ruby/1.8/webrick/httpserver.rb:104:in `service'
/usr/lib/ruby/1.8/webrick/httpserver.rb:65:in `run'
/usr/lib/ruby/1.8/webrick/server.rb:173:in `start_thread'
/usr/lib/ruby/1.8/webrick/server.rb:162:in `start'
/usr/lib/ruby/1.8/webrick/server.rb:162:in `start_thread'


最后在http://blog.caronsoftware.com/articles/2006/12/03/fckeditor-0-4-0-released#comment-1745找到了答案,這是一個BUG

解決方法 :

修改:vendor/plugins/fckeditor/app/controller/fckeditor_controller.rb
將原來的

unless?"#{file.class}"?==?"Tempfile"

改為
unless?"#{file.class}"?==?"Tempfile"?||?"#{file.class}"?==?"StringIO"





陳剛 2007-08-25 16:44 發表評論
]]>
mootools VS prototypehttp://www.tkk7.com/chengang/archive/2007/08/23/138780.html陳剛陳剛Thu, 23 Aug 2007 04:11:00 GMThttp://www.tkk7.com/chengang/archive/2007/08/23/138780.htmlhttp://www.tkk7.com/chengang/comments/138780.htmlhttp://www.tkk7.com/chengang/archive/2007/08/23/138780.html#Feedback0http://www.tkk7.com/chengang/comments/commentRss/138780.htmlhttp://www.tkk7.com/chengang/services/trackbacks/138780.html前天為了實現一個Lightbox的效果,搜了一些資料,引出了mootools這一個javascript庫(http://mootools.net/ )。其效果的確很酷,這個是它的常見效果實現一覽表http://demos.mootools.net/

我覺得mootools比prototype強的地方,就是它的理念更OO,重點表現在它把javascript、html、css完全分離開來,用mootools的話,html里干凈得找不到javascript的影子。javascript、html 分離,這很重要。

其次 ,mootools的文檔很不錯,在http://demos.mootools.net/ 這個效果一覽表中,你可以很輕松的看到實現效果的代碼。代碼清晰的分為三個部份javascript、html、css,你只要將這些代碼復制到你的項目中就能得到預期的效果。它的javascript代碼對于有java或OO基礎的人相當易懂。


再次,下載的mootools是壓過編碼壓縮的了的,這使得javascript文件更小,選擇所有部件后大約是30K。而prototype是100多K,當然prototype也可以用javascript壓縮工具壓縮一下。


唯一遺憾的是Rails默認支持的是prototype,而非mootools。當然我們也可以在Rails項目中拋棄prototype改用mootools,但rails那些對javascript做了封裝的helper方法就用不了。這是一個不小損失。





陳剛 2007-08-23 12:11 發表評論
]]>
Rails驗證碼圖片的實現http://www.tkk7.com/chengang/archive/2007/08/17/137683.html陳剛陳剛Fri, 17 Aug 2007 11:48:00 GMThttp://www.tkk7.com/chengang/archive/2007/08/17/137683.htmlhttp://www.tkk7.com/chengang/comments/137683.htmlhttp://www.tkk7.com/chengang/archive/2007/08/17/137683.html#Feedback0http://www.tkk7.com/chengang/comments/commentRss/137683.htmlhttp://www.tkk7.com/chengang/services/trackbacks/137683.html
在linux下生成圖片需要圖片處理軟件ImageMagick的Ruby語言RMagick庫支持。安裝RMagick最麻煩,我查了N多資料試了N次才安裝成功。
   1. 安裝ImageMagick:sudo apt-get install imagemagick
   2. 查看安裝結果:dpkg -l | grep magick
   3. 更新軟件包列表:sudo apt-get update
   4. 安裝圖片處理軟件包libmagick9-dev:sudo apt-get install libmagick9-dev ruby1.8-dev
   5. 安裝接口軟件包RMagick:sudo gem install rmagick
   6. 說明:如果出現問題或者錯誤請執行下面命令:sudo apt-get remove --purge libmagick9-dev

在irb里require 'RMagick'。如果返回true,表示安裝成功。

第二步:編碼

在models目錄創建一個proof_image.rb

require 'rubygems'
require 'RMagick'
class ProofImage
  include Magick
  attr_reader :text, :image
  Jiggle 
= 15
  Wobble 
= 15

  def initialize(len
=4)
    chars 
= ('a'..'z').to_a # + ('0'..'9').to_a
    text_array
=[]
    
1.upto(len) {text_array << chars[rand(chars.length)]}
    #background_type 
= "granite:" #花崗巖
    #background_type 
= "netscape:" #彩條
    #background_type 
= "xc:#EDF7E7" #指定背景色,例:xc:red
    #background_type 
= "null:" #純黑
    granite 
= Magick::ImageList.new('null:')
    canvas 
= Magick::ImageList.new
    canvas.new_image(
32*len, 50, Magick::TextureFill.new(granite))
    gc 
= Magick::Draw.new
    gc.font_family 
= 'times'
    gc.pointsize 
= 40
    cur 
= 10

    text_array.each{
|c|
      rand(
10> 5 ? rot=rand(Wobble):rot= -rand(Wobble)
      rand(
10> 5 ? weight = NormalWeight : weight = BoldWeight
      gc.annotate(canvas,
0,0,cur,30+rand(Jiggle),c){
        self.rotation
=rot
        self.font_weight 
= weight
        self.fill 
= 'green'
      }
      cur 
+= 30
    }
    @text 
= text_array.to_s
    @image 
= canvas.to_blob{
      self.format
="GIF"
    }

    #生成圖片文件
    #text.text(
00" ")
    #text.draw(canvas)
    #canvas.write('test.gif') #圖片位于項目根目錄下。也可以使用linux中的絕對路徑如:
/home/chengang/test.gif

  end
end


在一個controller里加入一個方法,方法的作用是向網頁提供圖片數據。我選擇創建一個專門的UtilController。

class UtilController < ApplicationController

  def proof_image
    proof_image 
= ProofImage.new
    session[:proof_text] 
= proof_image.text
    send_data proof_image.image, :type 
=> 'image/jpeg', :disposition => 'inline'
  end

end


以下是在頁面中的調用代碼:

輸入驗證碼:<%=text_field(:proof, :text, :maxlength=>4%>
<img id="img" src="/chen/util/proof_image">
<a href="#" onclick="changeImage();return false;">換一個驗證碼</a><br/>


其中changeImage()是一個javascript函數,因為換圖片時必須改變<img的src,否則瀏覽器不會執行UtilController的proof_image方法,而是從緩存中取得圖片數據。

function changeImage(){
  $(
"img").src = "/chen/util/proof_image?tmp=" +new Date().getTime(); // Math.random();
}


我的環境:ubuntu 7.04 + Rails 1.2.3 +Ruby 1.8.5



陳剛 2007-08-17 19:48 發表評論
]]>
學習REST on Rails的途徑http://www.tkk7.com/chengang/archive/2007/08/15/136905.html陳剛陳剛Wed, 15 Aug 2007 06:49:00 GMThttp://www.tkk7.com/chengang/archive/2007/08/15/136905.htmlhttp://www.tkk7.com/chengang/comments/136905.htmlhttp://www.tkk7.com/chengang/archive/2007/08/15/136905.html#Feedback0http://www.tkk7.com/chengang/comments/commentRss/136905.htmlhttp://www.tkk7.com/chengang/services/trackbacks/136905.html昨天開始接觸學習REST,是個新手。用一個下午的時間baidu了一些REST資料,又重點翻看 了javaeye所有關鍵詞是REST的貼子。在了解和學習之后,我認為REST是值得去嘗試的。

我學習REST的途徑如下:

1、學習REST,下面這一篇翻譯自<<RESTful Rails Development>>文檔基本就夠了。感謝yananay的辛苦翻譯,翻譯得相當流暢。
http://www.javaeye.com/topic/89133

2、其次是看別人是怎么用REST的,大家一致推薦beast網站,具體的內容在這個貼子上
http://www.javaeye.com/topic/39355

3、另外再附一篇Rails創始人DHH的演講翻譯稿,這讓我們能大概搞清楚REST是什么,它的初衷是什么:http://blog.csdn.net/myan/archive/2006/11/25/1413933.aspx

看完<RESTful Rails Development>就可以開始對自己的網站重構了,有不懂的地方再參考一下別人beast是怎么實現的。




陳剛 2007-08-15 14:49 發表評論
]]>
<Programming Ruby中文版> 讀后感http://www.tkk7.com/chengang/archive/2007/08/08/135135.html陳剛陳剛Wed, 08 Aug 2007 01:01:00 GMThttp://www.tkk7.com/chengang/archive/2007/08/08/135135.htmlhttp://www.tkk7.com/chengang/comments/135135.htmlhttp://www.tkk7.com/chengang/archive/2007/08/08/135135.html#Feedback1http://www.tkk7.com/chengang/comments/commentRss/135135.htmlhttp://www.tkk7.com/chengang/services/trackbacks/135135.html這是RoR 的兩本必讀書中的一本,兩本書都是Dave Thomas的主寫的。卓越網(已被亞馬遜收購)好象最近購書免郵費,所以我訂了一本,原價99,我只花了72元。由于是平郵,一周多后才收到書。800多頁的書相當厚實,紙張也很不錯。不過由于太厚,現在有從中間撕裂為兩半的危險。

書分四大部份,第一部分講語法基礎,這部分是需要認真讀的。這部份寫得很細,很不錯,需要認真做一些筆記。

第二部分講一些較高級的較邊緣性的東西,這部分可以快速瀏覽或跳過。我認真這個部份很多東西都可省去或簡化,比如第15章講irb的根本沒必要這么細,誰會經常用irb來寫ruby程序呢?而第17章講GEM庫,這對軟件產品的打包發行比較重要,卻又缺乏可操作性,讀來不知所云 。

第三部分又回到了語法,但更象是第一部份的讀書筆記。真搞不懂為什么作者要單獨出來成為一大部份,從寫作的角度來說,把它里面的新知識點融入到第一部份中會更好。

第四部分是枯燥的API參考,也是需要重點了解熟悉的,不清楚API還編個什么勁。不過對于英文版的讀者來說,這似乎完全沒有必要,因為網上有最新API文檔可查閱,內容基本是一樣的。當然對于國內讀者來說,這部份翻譯成中文還是有價值的,免去了讀英文API文檔的痛苦。

如果你有JAVA的基礎,書的前三部份可以在四天內讀完。不過我覺得第一部份應該多看幾遍,而第四部份也需經常通讀,今后編程會常常翻查API。 總的來說,這本書對于學習Ruby還是很有用的,關鍵是翻譯得也還不錯,讀起來牙不酸胃不痛,所以值得一買。








陳剛 2007-08-08 09:01 發表評論
]]>
用AJAX實現氣泡提示http://www.tkk7.com/chengang/archive/2007/07/31/133508.html陳剛陳剛Tue, 31 Jul 2007 07:32:00 GMThttp://www.tkk7.com/chengang/archive/2007/07/31/133508.htmlhttp://www.tkk7.com/chengang/comments/133508.htmlhttp://www.tkk7.com/chengang/archive/2007/07/31/133508.html#Feedback6http://www.tkk7.com/chengang/comments/commentRss/133508.htmlhttp://www.tkk7.com/chengang/services/trackbacks/133508.html                                    文/陳剛 www.chengang.com.cn (轉載請注明)

這個效果的實現是以網站http://www.panic.com/coda/為模仿對象(選擇Download可以看到氣泡提示效果),然后重新用Rails中的prototype.js來實現。

HTML頁面的代碼:
<span id="content_<%=o.id%>" style="display:none">
    
<!-- Download Popup style=opacity: 0; visibility: hidden;-->
<table style="top:500px; left:600px;" class="popup">
  <tbody>
    <tr>
      <td class="corner" id="topleft"></td>
      <td class="top"></td>
      <td class="corner" id="topright"></td>
    </tr>
    <tr>
      <td class="left"></td>
      <td><table class="popup-contents">
        <tbody>
            <tr>
              <td><%=o.content%></td>
            </tr>
        </tbody>
      </table></td>
      <td class="right"></td>    
    </tr>
    <tr>
      <td id="bottomleft" class="corner"></td>
      <td class="bottom"><img src="http://www.tkk7.com/images/bubble-tail2.png" alt="popup tail" height="29" width="30"></td>
      <td class="corner" id="bottomright"></td>
    </tr>
  </tbody>
</table>
<!-- end download popup -->
</span>


CSS的代碼(涉及到的相關圖片:bubble.rar):
/* Bubble pop-up */
.popup {
    position: absolute;
    z
-index: 50;
    border
-collapse: collapse;
       
/* width:500px;
    visibility: hidden; 
*/
}

.popup td.corner {height: 15px;    width: 19px;}
.popup td#topleft { background
-image: url(/images/bubble-1.png); }
.popup td.top { background
-image: url(/images/bubble-2.png); }
.popup td#topright { background
-image: url(/images/bubble-3.png); }
.popup td.left { background
-image: url(/images/bubble-4.png); }
.popup td.right { background
-image: url(/images/bubble-5.png); }
.popup td#bottomleft { background
-image: url(/images/bubble-6.png); }
.popup td.bottom { background
-image: url(/images/bubble-7.png); text-align: center;}
.popup td.bottom img { display: block; margin: 
0 auto; }
.popup td#bottomright { background
-image: url(/images/bubble-8.png); }

.popup table.popup
-contents {
    font
-size: 12px;
    line
-height: 1.2em;
    background
-color: #fff;
    color: #
666;
    font
-family: "Lucida Grande""Lucida Sans Unicode""Lucida Sans", sans-serif;
    }

table.popup
-contents th {
    text
-align: right;
    text
-transform: lowercase;
    }
    
table.popup
-contents td {
    text
-align: left;
    }

然后給需要氣泡提示的加上鼠標事件:
 <span class="l1" onmouseover="Element.show('content_<%=o.id%>')" onmouseout="Element.hide('content_<%=o.id%>')"><%=article_link_to(o.title,o.id)%></span>



二、繼續改進
氣泡提示的外圍HTML表格代碼可以改由javascript來動態生成,這樣可以縮小一些頁面的總HTML大小。

HTML頁面代碼改為:
<span id="content_<%=o.id%>" style="display:none"><%=o.content%></span>
其他想法:本來打算把文章內容(氣泡顯示的內容),直接傳入javascript函數showPopup里。但由于其字符串較復雜,需要對一些特殊字符進行轉義才可以當成字符串傳入,而轉義需要通寫Rails方法來實現,大量的字符搜索替換恐怕會增加服務器的負擔。所以這里還是用一個html元素暫存氣泡內容。


然后給需要氣泡提示的加上鼠標事件。
    <span class="l1" onmouseover="showPopup('content_<%=o.id%>',event);" onmouseout="hidePopup()"><%=article_link_to(o.title,o.id)%></span>

CSS的代碼不變。

寫兩個javascript函數:
function showPopup(element_id,event){
  
var div = createElement("div");  
  div.id 
= "popup";
  
//div.style.display="none";
  var popup = $(element_id);
  
//取得鼠標的絕對坐標
  var evt = event ? event : (window.event ? window.event : null);  
  
var x = Event.pointerX(evt)+5;
  
var y = Event.pointerY(evt)+5;
  div.innerHTML
='\
        
<table style="top:' + y + 'px; left:' + x + 'px;" class="popup">\
          
<tbody>\
            
<tr>\
              
<td class="corner" id="topleft"></td>\
              
<td class="top"></td>\
              
<td class="corner" id="topright"></td>\
            
</tr>\
            
<tr>\
              
<td class="left"></td>\
              
<td><table class="popup-contents">\
                
<tbody>\
                    
<tr>\
                      
<td>+ popup.innerHTML + '</td>\
                    
</tr>\
                
</tbody>\
              
</table></td>\
              
<td class="right"></td>\
            
</tr>\
            
<tr>\
              
<td id="bottomleft" class="corner"></td>\
              
<td class="bottom"><!--<img src="/images/bubble-tail2.png" alt="popup tail" height="29" width="30">--></td>\
              
<td class="corner" id="bottomright"></td>\
            
</tr>\
          
</tbody>\
        
</table>';
  document.body.appendChild(div);
  
//Element.show("popup");
}

function hidePopup(){
  Element.remove(
"popup");
}

function createElement(element) {
    if (typeof document.createElementNS != 'undefined') {
        return document.createElementNS('http://www.w3.org/1999/xhtml', element);
    }
    if (typeof document.createElement != 'undefined') {
        return document.createElement(element);
    }
    return false;
}


在javascript中漸顯Effect.Appear有一點問題,所以就沒再用。

效果如下圖所示:








陳剛 2007-07-31 15:32 發表評論
]]>
rails中使用ajax時的分頁實現http://www.tkk7.com/chengang/archive/2007/07/30/133396.html陳剛陳剛Mon, 30 Jul 2007 09:53:00 GMThttp://www.tkk7.com/chengang/archive/2007/07/30/133396.htmlhttp://www.tkk7.com/chengang/comments/133396.htmlhttp://www.tkk7.com/chengang/archive/2007/07/30/133396.html#Feedback0http://www.tkk7.com/chengang/comments/commentRss/133396.htmlhttp://www.tkk7.com/chengang/services/trackbacks/133396.htmlhttp://ruby-lang.org.cn/forums/viewthread.php?tid=206&extra=page%3D1&page=2

但如果使用ajax則分頁的實現需要改動一下,如下所示。

      共<b><%=@article_pages.page_count%></b>頁:&nbsp;

      
<%=if @article_pages.current!=@article_pages.first_page
         link_to_remote(
"首頁",:update => "articleList",
            :url 
=> {:action => 'list',:subcategory_id => @subcategory.id,:page => @article_pages.first_page})
      
else
      
"首頁"
      end
%>

      
<%=if @article_pages.current.previous
      link_to_remote(
"上一頁",:update => "articleList",
          :url 
=> {:action => 'list',:subcategory_id => @subcategory.id,:page => @article_pages.current.previous})
      
else
      
"上一頁"
      end 
-%>



      
<%=pagination_links_each(@article_pages, :window_size => 5do | page |
      link_to_remote(
"[#{page}]", :update => "articleList",
                           :url 
=> {:action => 'list',:subcategory_id => @subcategory.id,:page => page}) 
      end
%>

      
<%=if @article_pages.current.next
      link_to_remote(
"下一頁",:update => "articleList",
                :url 
=> {:action => 'list',:subcategory_id => @subcategory.id,:page => @article_pages.current.next})
      
else
      
"下一頁"
      end 
-%>

      
<%=if @article_pages.current!=@article_pages.last_page
      link_to_remote(
"末頁",:update => "articleList",
      :url 
=> {:action => 'list',:subcategory_id => @subcategory.id,:page => @article_pages.last_page})
      
else
      
"末頁"
      end
%>


然后再優化一下,把這些代碼提取成一個公共函數,放在application_helper里,以便其他頁面也能共享。代碼如下:

  def ajax_pagination_links(pages,update,url)
    links 
= []
    links 
<< "共<b>#{pages.page_count}</b>頁"
    
return links[0if pages.page_count==1
    links 
<< ":&nbsp;"

    
if pages.current!=pages.first_page
      url[:page] 
= pages.first_page
      links 
<< link_to_remote("首頁", :update => update, :url => url)
    
else
      links 
<< "首頁"
    end
 
    
if pages.current.previous
      url[:page] 
= pages.current.previous
      links 
<< link_to_remote("上一頁", :update => update, :url => url)
    
else
      links 
<< "上一頁"
    end

    links 
<< pagination_links_each(pages, :window_size => 5do |page|
                url[:page] 
= page
                link_to_remote(
"[#{page}]", :update => update, :url => url) 
            end

    
if pages.current.next
      url[:page] 
= pages.current.next
      links 
<< link_to_remote("下一頁",:update => update, :url => url)
    
else
      links 
<< "下一頁"
    end

    
if pages.current!=pages.last_page
      url[:page] 
= pages.last_page
      links 
<< link_to_remote("末頁",:update => update, :url => url)
    
else
      links 
<< "末頁"
    end
    
    links.join(
" ")
  end

以后在頁面里只需要加上這樣一句即可
     <%=ajax_pagination_links(@article_pages, "articleList", {:action => 'list',:subcategory_id => @subcategory.id})%>



陳剛 2007-07-30 17:53 發表評論
]]>
[遷移到Linux] 遷移mysqlhttp://www.tkk7.com/chengang/archive/2007/06/12/123491.html陳剛陳剛Mon, 11 Jun 2007 16:33:00 GMThttp://www.tkk7.com/chengang/archive/2007/06/12/123491.htmlhttp://www.tkk7.com/chengang/comments/123491.htmlhttp://www.tkk7.com/chengang/archive/2007/06/12/123491.html#Feedback2http://www.tkk7.com/chengang/comments/commentRss/123491.htmlhttp://www.tkk7.com/chengang/services/trackbacks/123491.html  最近這段時間關于版權的問題,越來越重視了,已經成為國與國之間的大事,必竟這關系于一大筆$。雖然,我的XP是正版的,但還是考慮遷移到linux上來,并把linux做為今后的工作環境。咱也要爭口氣,說我盜版,那我不用你的不就成了。我選用的linux版本是ubuntu 7.04,這篇博客就是在新操作系統上寫的。


遷移動linux上還是碰到了不少問題,主要還是習慣的問題。雖然ubuntu的桌面環境已經非常不錯了,但很多編程方面的軟件還是命令行式的,比如mysql。




安裝MySQL



sudo apt-get install mysql-server mysql-client


root原密碼為空,給它加個密碼

mysqladmin -uroot -password 123456


導入SQL腳本

mysql -uroot -p123456 < db/create_table.sql


重啟動mysql服務
mysqladmin -uroot -p123456 shutdown
sudo mysqld&


中文亂碼的解決
修改mysql配置文件
sudo vim /etc/mysql/my.cnf

增加紅色一句

datadir = /var/lib/mysql

tmpdir = /tmp

language = /usr/share/mysql/english

default-character-set = utf8

skip-external-locking


現象:在用命令行導入建表與插入數據的腳本后,所得數據還是亂碼。但在RadRails中用insert插入數據卻中文顯示正常,看來是mysql命令行客戶端的原因。在SQL腳本頭加上如下一句,可以讓mysql命令行客戶端識別編碼,正常導入中文。

SET NAMES 'utf8';




mysql的GUI客戶端可以使用mysql官方的mysql-query-browser。在ubuntu的新立得管理器里可以裝。



陳剛 2007-06-12 00:33 發表評論
]]>
Ruby on Rails筆記_v0.1http://www.tkk7.com/chengang/archive/2007/05/13/117075.html陳剛陳剛Sat, 12 May 2007 16:46:00 GMThttp://www.tkk7.com/chengang/archive/2007/05/13/117075.htmlhttp://www.tkk7.com/chengang/comments/117075.htmlhttp://www.tkk7.com/chengang/archive/2007/05/13/117075.html#Feedback3http://www.tkk7.com/chengang/comments/commentRss/117075.htmlhttp://www.tkk7.com/chengang/services/trackbacks/117075.html“讀不如做,做不如寫”,這一直是我學習技術所喜歡的方式。我是一個健忘的人,把知識寫成文章后,自己遺忘時查閱也就方便了很多,畢竟是自己寫的東西一查就能記起大部份來。此文檔(PDF格式) 是我學習Ruby on Rails技術的綜合,有讀書筆記、有心得、有自創教程、有一些問題的解決經驗,統統分門別類集合在了一起。由于時間倉促,所以有些地方寫得很簡略,排版有些亂,錯誤肯定也不少。寄希望于以后不斷更新此文檔,爭取更完善起來。



Ruby on Rails筆記,下載:  V0.1 、   V0.2





陳剛 2007-05-13 00:46 發表評論
]]>
Rails學習筆記(7)實現分頁,及數據庫模型命名限制http://www.tkk7.com/chengang/archive/2007/05/08/116053.html陳剛陳剛Tue, 08 May 2007 14:09:00 GMThttp://www.tkk7.com/chengang/archive/2007/05/08/116053.htmlhttp://www.tkk7.com/chengang/comments/116053.htmlhttp://www.tkk7.com/chengang/archive/2007/05/08/116053.html#Feedback0http://www.tkk7.com/chengang/comments/commentRss/116053.htmlhttp://www.tkk7.com/chengang/services/trackbacks/116053.html
先在Action使用paginate方法,如下。
其中得到的數據記錄會在@articles變量里,頁的信息在@article_pages變量里。
paginate方法的第一參數是數據表名,order_by根據id排倒序,conditions是查詢條件,per_page是每頁三條記錄。
    @article_pages,@articles = paginate(:articles, 
                                        :order_by 
=> 'id DESC'
                                        :conditions 
=> "user_id=" + user_id, 
                                        :per_page 
=> 3)

接著在頁面里就可以把@articles變量里的記錄顯示出來,而在*.rhtml文件里顯示分頁的那一欄的代碼為
<%= pagination_links(@article_pages)%>

缺點是分頁欄的式樣固定,只列出了頁碼,沒有列出上一頁、下一頁這樣的翻頁的按鈕。不過,研究一下pagination_links方法的源代碼,自己仿造寫一個應該很簡單。


---------------------------------

今天還碰到一個問題,我把表titles改名為modules后,模型文件名為module.rb,其他部份也做了修改。運行后出了錯,出錯信息是Module.class沒有find方法(我在action調用find方法)。如下:
 NoMethodError in SiteController#index

undefined method `find
' for Module:Class

RAILS_ROOT: .
/script/../config/..
Application Trace 
| Framework Trace | Full Trace

#{RAILS_ROOT}
/app/controllers/site_controller.rb:21:in `header'
#{RAILS_ROOT}/app/controllers/site_controller.rb:5:in `index'
-e:4:in `load'
-e:4


多方嘗試后發現數據庫模型類不允許起名為module(這應該是rails內部的一個類,或者是rails是一個關鍵字),最后的解決辦法是加一個下劃線后綴,然后用set_table_name指定映射的表名。文件名:module_.rb
class Module_ < ActiveRecord::Base
  set_table_name 
"modules"
end




陳剛 2007-05-08 22:09 發表評論
]]>
XHTML+CSS (2) 一個通用頁面框架http://www.tkk7.com/chengang/archive/2007/04/19/111895.html陳剛陳剛Thu, 19 Apr 2007 05:22:00 GMThttp://www.tkk7.com/chengang/archive/2007/04/19/111895.htmlhttp://www.tkk7.com/chengang/comments/111895.htmlhttp://www.tkk7.com/chengang/archive/2007/04/19/111895.html#Feedback0http://www.tkk7.com/chengang/comments/commentRss/111895.htmlhttp://www.tkk7.com/chengang/services/trackbacks/111895.html每個頁面都可以用的XHTML模板(擴展點為*.html):
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>子在川上曰</title>
<link href="main.css" rel="stylesheet" type="text/css" media="screen" />
</head>
<body>
       。。。。。。。。主頁內容
</body>
</html>

用DIV+CSS來排版,的確要比過去表格方式利于維護。一般的方式是用DIV搭出頁面骨架,然后用CSS慢慢潤飾。看了《禪意花園》的讀試第一章,再去它的網站看了看,這是它的原始頁面:http://www.csszengarden.com/tr/chinese/。禪意花園提供了固定的XHTML文檔結構,而各設計師可以基于此文檔設計出CSS能改變頁面風格,這些頁面風格很出彩:http://www.mezzoblue.com/zengarden/alldesigns/,從中可見CSS的頁面修飾能力強到超出我們想像。

我也簡單用DIV+CSS寫了一個簡單的頁面框架:http://www.tkk7.com/Files/chengang/xhtml_css_demo.rar。這個DEMO在IE7下顯示正常,在FireFox3下則有點問題。但用Amaya檢查,沒有發現格式錯誤。有高手懂的幫指出一下。

補:
li列表在FF3下顯示出圓點的解決,加式樣:list-style:none;


陳剛 2007-04-19 13:22 發表評論
]]>
Rails學習筆記(6)中文亂碼的解決http://www.tkk7.com/chengang/archive/2007/04/19/111867.html陳剛陳剛Thu, 19 Apr 2007 03:41:00 GMThttp://www.tkk7.com/chengang/archive/2007/04/19/111867.htmlhttp://www.tkk7.com/chengang/comments/111867.htmlhttp://www.tkk7.com/chengang/archive/2007/04/19/111867.html#Feedback0http://www.tkk7.com/chengang/comments/commentRss/111867.htmlhttp://www.tkk7.com/chengang/services/trackbacks/111867.html環境:
。MySQL 5.0,MySQL的環境配置為UTF8,建表也全部使用UTF8。
。IE6.0、FireFox 2.0.2
。Ruby 1.8.5 + rails 1.2.3

錯誤現象:
。用MySQL Query Browser查看MySQL數據,中文顯示正常。
。頁面顯示為亂碼,原來是中文的地方都變成了一個長方塊
。手工調整瀏覽器的頁面編碼,可以使用頁面正常顯示。但刷新后又是亂碼。

解決方法:修改config/database.yml,加入一句編碼設置如下。

 

development:
  adapter: mysql
  database: chensite_development
  encoding: utf8
  username: root
  password: 
123456
  host: localhost

 

這時從數據庫讀取的數據顯示正常了,但*.rhtml里的原中文卻顯示變成了亂碼。據說將*.rhtml用記事本重新保存為utf-8格式可以解決,而我是用Radrails,右擊項目,在它的屬性頁的info項的text file encoding改為UTF-8。這時*.rhtml文件里的中文會變成亂碼,所以最好備份一下,然后將備份的文件內容一個個的復制粘貼過來。致此終于完美解決了中文亂碼問題。


注:

1。有些文章說要修改application.rb,在before_filter加入字符過濾代碼。我以前也試過,可行。但我覺得還是修改database.yml來得簡單一些。


2。有些文章說要同時在*.rhtml里加上如下編碼設置。我發現這一句可加可不加,對頁面編碼顯示沒有任何影響。
<meta http-equiv="Content-type" content="text/html; charset=utf-8" />


3。還有的人說修改environment.rb加入兩行 $KCODE = 'u' 和 require 'jcode' 。這里似乎沒有必要。也許這是老版Rails的解決方法。

 

4。有的人說在建表的時候不能用InnoDB,但我的建表語句如下,是用InnoDB。沒有發現問題。

create table modules (
 id             
int           not null auto_increment,
 ..........

 expanded       tinyint(
1)    default 0,
 primary key (id)
)ENGINE
=InnoDB DEFAULT CHARSET=utf8;



陳剛 2007-04-19 11:41 發表評論
]]>
Rails學習筆記(5)第6、7、8章摘要http://www.tkk7.com/chengang/archive/2007/04/10/109408.html陳剛陳剛Tue, 10 Apr 2007 01:47:00 GMThttp://www.tkk7.com/chengang/archive/2007/04/10/109408.htmlhttp://www.tkk7.com/chengang/comments/109408.htmlhttp://www.tkk7.com/chengang/archive/2007/04/10/109408.html#Feedback0http://www.tkk7.com/chengang/comments/commentRss/109408.htmlhttp://www.tkk7.com/chengang/services/trackbacks/109408.html
執行SQL腳本:mysql depot_development < db/create.sql
創建三個庫,分別用于開發、測試、生產:depot_development、depot_test、depot_production。
每個表都應該帶一個和業務無關的ID字段。
在rails配置數據庫的連接:config\database.yml。密碼之前冒號之后要間隔一個空格。

ruby script/generate scaffold Product Admin,針對Product表產生一整套的網頁程序(增刪改),Admin是控制器名
ruby script/generate controller Store index   創建一個名為Store的控制器,并含有一個index() Action方法。


啟動WEB服務:ruby script/server。(http://localhost:3000/admin


模型類:
。validates_presence_of  :title, :desc, :image_url   必須不為空
。validates_numericality_of :price  必須是數字
。validates_uniqueness_of   :title   必須唯一
。validates_format_of       :image_url,
                            :with    => %r{^http:.+\.(gif|jpg|png)$}i,
                            :message => "must be a URL for a GIF, JPG, or PNG image"  文件名必須是圖片文件的擴展名
。模型保存到數據庫之前會調用validate方法,例:
  def validate
    errors.add(:price, 
"should be positive") unless price.nil? || price > 0.0
  end



ActiveRecord的方法屬性:
。content_columns 得到所有字段。content_columns.name字段名
。日期在今天之前,按日期倒序排列。self表示它是一個類方法(靜態方法)。
  def self.salable_items
    find(:all, :conditions 
=> "date_available <= now()", :order => "date_available desc")
  end


以下為鏈接,效果相當于以前的“http://..../show.jsp?id=11
      <%= link_to 'Show', :action => 'show', :id => product %><br/>
      
<%= link_to 'Edit', :action => 'edit', :id => product %><br/>
      
<%= link_to 'Destroy', { :action => 'destroy', :id => product }, :confirm => "Are you sure?" %>


<%=  if @product_pages.current.previous 
       link_to(
"Previous page", { :page => @product_pages.current.previous })
     end
%>

<%= if @product_pages.current.next 
      link_to(
"Next page", { :page => @product_pages.current.next })
    end
%>


truncate(product.desciption, 80)  顯示產品描述字段的摘要(80個字符)
product.date_available.strftime("%y-%m-%d") 日期字段的格式化顯示
sprintf("%0.2f", product.price) 數值的格式化顯示, number_to_currency方法也有類似功能

public/stylesheets 目錄保存了網頁所用的CSS式樣表。用ruby script/generate scaffold ....生成框架代碼的網頁自動使用scaffold.css


布局模板
。app/views/layouts目錄中創建一個與控制器同名的模板文件store.rhtml,則控制器下所有網頁都會使用此模板

 

<html>
    
<head>
      
<title>Pragprog Books Online Store</title>
      
<%= stylesheet_link_tag "scaffold""depot", :media => "all" %>
    
</head>
    
<body>
        
<div id="banner">
            
<img src="/images/logo.png"/>
            
<%= @page_title || "Pragmatic Bookshelf" %>
        
</div>
        
<div id="columns">
            
<div id="side">
                
<a href="http://www.">Home</a><br />
                
<a href="http://www./faq">Questions</a><br />
                
<a href="http://www./news">News</a><br />
                
<a href="http://www./contact">Contact</a><br />
            
</div>
            
<div id="main">
                
<% if @flash[:notice] -%>
                  
<div id="notice"><%= @flash[:notice] %></div>
                
<% end -%>
                
<%= @content_for_layout %>
            
</div>
        
</div>
    
</body>
</html>

。<%= stylesheet_link_tag "scaffold""depot", :media => "all" %>生成指向scaffold.css、depot.css兩個式樣表的<link>標簽
@page_title 各個頁面標題變量
@flash[:notice] 提示性的信息(key=notice),這是一個公共變量。
。<%= @content_for_layout %> 位置嵌入顯示控制器內名網頁。由于其他網頁變成了模板的一部份,所以其<html>等標簽應該去掉。



store_controller.rb ,當從session里取出某購物車不存在,則新建一個,并存入session。最后把此購物車賦給變量cart。

  def find_cart
    @cart 
= (session[:cart] ||= Cart.new)
  end


ruby  script/generate  model  LineItem,創建一個LineItem的數據模型,附帶還會創建相應的測試程序。

store_controller.rb:

  def add_to_cart
    product 
= Product.find(params[:id])
    @cart.add_product(product)
    redirect_to(:action 
=> 'display_cart')
  rescue
    logger.error(
"Attempt to access invalid product #{params[:id]}")
    redirect_to_index(
'Invalid product')
  end

。params是URL的參數數組
。redirect_to轉向語句
。rescue 異常,相當于Java的Exception
。redirect_to_index是application.rb中的一個方法,這個文件里的方法是各控制器公開的。
。logger是rails內置的變量。

class Cart

  attr_reader :items
  attr_reader :total_price
  
  def initialize
    empty
!
  end

  def add_product(product)
    item 
= @items.find {|i| i.product_id == product.id}
    
if item
      item.quantity 
+= 1
    
else
      item 
= LineItem.for_product(product)
      class Cart

  # An array of LineItem objects
  attr_reader :items

  # The total price of everything added to this cart
  attr_reader :total_price
 
  # Create a new shopping cart. Delegates this work to #empty!
  def initialize
    empty!
  end

  # Add a product to our list of items. If an item already
  # exists for that product, increase the quantity
  # for that item rather than adding a new item.
  def add_product(product)
    item = @items.find {|i| i.product_id == product.id}
    if item
      item.quantity += 1
    else
      item = LineItem.for_product(product)
      @items << item
    end
    @total_price += product.price
  end

  # Empty the cart by resetting the list of items
  # and zeroing the current total price.
  def empty!
    @items = []
    @total_price = 0.0
  end
end

    end
    @total_price 
+= product.price
  end

  def empty
!
    @items 
= []
    @total_price 
= 0.0
  end
end 


。由于Cart沒有對應的數據表,它只是一個普通的數據類,因此要定義相應的屬性。
。@items << item 把對象item加入到@items數組
。@items=[]   空數組


如果出現SessionRestoreError錯誤,則檢查application.rb是否做了如下的模型聲明。因為對于動態語句,session把序列化的類取出時,否則是無法知道對象類型的,除非聲明一下。

class ApplicationController < ActionController::Base
  model :cart
  model :line_item
end


<%  ... -%>  -%>相當于一個換行符


@items.find(|i| i.product_id == product.id)  |i|的作用應該相當于@items數組中的一個元素(書上沒有提到,要查一下ruby語法)。


if @items.empty?   判斷數組是否為空數組

flash[:notice] flash可以在同一個Session的下一個請求中使用,隨后這些內容就會被自動刪除(下一個的下一個就被清空了??)。
實例變量是代替不了flash的,因為IE無狀態的特性,在下一個請求中,上一個請求的實例變量已失效。


當異常沒有被任何程序捕捉,最后總會轉到ApplicationController的rescue_action_in_public()方法


各視圖可以使用appp/helpers目錄下的各自相應的輔助程序中提供的方法。

 



陳剛 2007-04-10 09:47 發表評論
]]>
Rails學習筆記(4)數據庫配置及頁面讀取http://www.tkk7.com/chengang/archive/2007/04/09/109255.html陳剛陳剛Mon, 09 Apr 2007 06:36:00 GMThttp://www.tkk7.com/chengang/archive/2007/04/09/109255.htmlhttp://www.tkk7.com/chengang/comments/109255.htmlhttp://www.tkk7.com/chengang/archive/2007/04/09/109255.html#Feedback0http://www.tkk7.com/chengang/comments/commentRss/109255.htmlhttp://www.tkk7.com/chengang/services/trackbacks/109255.html開始在MySQL中創建數據庫,分別用于:開發、測試、產品

create database chensite_development;
create database chensite_test;
create database chensite_production;

在開發庫中建表和插入數據:
use chensite_development;

drop table 
if exists titles;
create table titles (
 id             
int           not null auto_increment,
 name           varchar(
100)  not null,
 url            varchar(
200)  default NULL,
 parent_id      
int           default 0,
 expanded       tinyint(
1)    default 0,
 level          tinyint(
1)    default 0,
 primary key (id)
)ENGINE
=InnoDB DEFAULT CHARSET=utf8;

LOCK TABLES titles WRITE;
INSERT INTO titles VALUES(
1,'AAAAAAAAA','http:\\www.AAAAAAAAA.com.cn',0,0,1);
INSERT INTO titles VALUES(
2,'BBBBBBBBB','http:\\www.BBBBBBBBB.com.cn',0,0,1);
INSERT INTO titles VALUES(
3,'CCCCCCCCC','http:\\www.CCCCCCCCC.com.cn',0,0,1);
INSERT INTO titles VALUES(
4,'關于','http:\\www.DDDDDDDDD.com.cn',0,0,1);

INSERT INTO titles VALUES(
5,'EEEEEEEEE','http:\\www.EEEEEEEEE.com.cn',2,0,2);
INSERT INTO titles VALUES(
6,'FFFFFFFFF','http:\\www.FFFFFFFFF.com.cn',2,0,2);
INSERT INTO titles VALUES(
7,'GGGGGGGGG','http:\\www.GGGGGGGGG.com.cn',2,0,2);
INSERT INTO titles VALUES(
8,'HHHHHHHHH','http:\\www.HHHHHHHHH.com.cn',2,0,2);


UNLOCK TABLES;

配置數據庫連接:  config\database.yml,主要是給連接三個數據庫的root用戶輸入密碼,在輸入密碼時要注意:"password:"和密碼"123456"之間要有一個空格,密碼之后不要有空格,否則無法啟動WEB服務。

# MySQL (default setup).  Versions 4.1 and 5.0 are recommended.
#
# Install the MySQL driver:
#   gem install mysql
# On MacOS X:
#   gem install mysql 
-- --include=/usr/local/lib
# On Windows:
#   gem install mysql
#       Choose the win32 build.
#       Install MySQL and put its 
/bin directory on your path.
#
# And be sure to use 
new-style password hashing:
#   http:
//dev.mysql.com/doc/refman/5.0/en/old-client.html
development:
  adapter: mysql
  database: chensite_development
  username: root
  password: 
123456
  host: localhost

# Warning: The database defined as 
'test' will be erased and
# re
-generated from your development database when you run 'rake'.
# Do not set 
this db to the same as development or production.
test:
  adapter: mysql
  database: chensite_test
  username: root
  password: 
123456
  host: localhost

production:
  adapter: mysql
  database: chensite_production
  username: root
  password: 
123456
  host: localhost

接下來創建一個能夠顯示數據庫數據的頁面。Rails是MVC模式的編程方式。
首先創建數據模型:app\models\title.rb
class Title < ActiveRecord::Base
end
  • 數據庫titles(小寫復數),文件名title.rb(小寫單數),類名Title(大寫單數)
  • 大寫方式--單詞第一個字母為大寫。小寫方式--每個單詞用下劃線分開。
  • 模型類中不必定義屬性,它會自動以數據庫字段為屬性。
  • set_table_name "table1" 定義對應的表
  • set_primary_key "name" 改默認的ID主鍵為name,不過以后name字段就用成id,如:o.id="chengang"

創建視圖:views\homepage\index.rhtml,顯示出title表所有記錄的id和name值

<html>
<body>
    
<h1>ChenGang's Site</h1>

<% for title in @titles %>

    
<%= title.id %>__<%= title.name %><br/>

<% end %>
</body>
</html>

視圖中用到的@titles變量來自于我們自己創建的如下控制器: app\controllers\homepage_controller.rb。Rails中控制器中的變量可以在視圖中使用(這是否會產生變量污染的問題呢,還待以后再體驗)

class HomepageController < ApplicationController
  def index
    @titles 
= Title.find(:all)
  end
end
  • Homepage和視圖的目錄名homepage相關
  • index方法和視圖的文件名index.rhtml相關
  • 用index可以省略訪問地址中的action(action默認為index action)

最后啟動Web服務器后訪問:http://localhost:3000/homepage 

 



陳剛 2007-04-09 14:36 發表評論
]]>
Rails學習筆記(3)前四章摘記http://www.tkk7.com/chengang/archive/2007/04/06/108997.html陳剛陳剛Fri, 06 Apr 2007 11:10:00 GMThttp://www.tkk7.com/chengang/archive/2007/04/06/108997.htmlhttp://www.tkk7.com/chengang/comments/108997.htmlhttp://www.tkk7.com/chengang/archive/2007/04/06/108997.html#Feedback0http://www.tkk7.com/chengang/comments/commentRss/108997.htmlhttp://www.tkk7.com/chengang/services/trackbacks/108997.html
下載Ruby的網址:http://rubyinstaller.rubyforge.org  檢查:ruby -v
安裝Rails的命令:gem install rails -include-dependencies 要注意網絡通暢。
更新Rails的命令: gem update rails
創建一個名為chensite的項目,命令:rails chensite
啟動內建的WEB服務器,先進入chensite目錄,再輸入命令:ruby script/server,訪問http://localhost:3000

-----------------------
書中都是用文本編輯器來編輯代碼,其實用RadRails這個IDE(Eclipse插件)更方便。
RadRails下載:http://radrails.sourceforge.net,我用的是radrails-0.7.1-win32.zip,解壓后就可以用了。
下面講一下它的配置,主要是在首選項窗口里設置。另注:除了配置ruby.exe有擴展名以外, 其他設定都沒有擴展名。


Mongrel是WEB服務器,這里可不設置。一般是用Apache做前端請求轉發,后端用mongrel做集群,以實現大負荷訪問。




在Eclipse右下角的Server視圖可以啟動WEB服務器。
創建一個Controller,在書中是這個命令:ruby script/generate controller say
Eclipse中的方式則如下圖所示:


在Eclipse中沒有專門用于rhtml文件的新建項,以普通文件方式創建即可。不過,提供RHTML的編輯器,內含代碼完成助手(Content Assist),代碼提示功能不強,只會提示一些基本的語法流程框架,沒有象JAVA編輯器那種類的方法的提示。


創建一個say控制器后,將say_controller.rb類如下
class SayController < ApplicationController
  def hello
    puts 
"chengang of puts"
    @blogsite
="www.chengang.com.cn"
    
3.downto(1)  do  |count|  #每次減1,從3循環到1 (32、1共三次循環)
      puts count
      puts 
"#{count} " + @blogsite
    end
    
  end
end

hello相當于一個Action,不過要顯示WEB頁面(http://localhost:3000/say/hello )還需要在一個rhtml文件:views/say/hello.rhtml

<html>
<head>
    
<title>Hello,Rails!<title>
</head>
<body>
    
<h1>Hello from Rails! </h1>
    
<%=Time.now%> <br/><!--now方法不用括號-->
    
<%=@blogsite%> <!--可以直接使用SayController中的變量-->
    
<%= link_to "bye bye", :action=>"goodbye"%>
</body>
</html>

。link_to除了action,還可以定義controller,以及action的參數
。link_to "About", :controller=>"showpage", :action=>"about", :id=>11  則生成的url為 http://.../showpage/about/11
。如果把上一個的id改為... :name=>"glchengang" ,則生成的url為http://.../showpage/about?name="glchengang"。和前一個url比較得知id是默認參數,不顯示。

<%=Time.now%> 顯示當前時間
 
h()方法用于輸出包含%<>等字符

1.hour.from_now 從現在過去1小時后的時間。數字也是一個對象,也具有方法。

3.times do  #三次循環
  puts 
"chengang"
end


3.downto(1do |count| #每次減1,從3循環到1 。共三次循環,count是變量
  puts count
end


<%= link_to "bye bye", :action=>"goodbye"%> 一個指向當前控制器say的goodbye這個Action的鏈接


---------------------------------------
www.tkk7.com對FirFox支持不太好,在編輯文章復制粘貼時,平白彈出一個窗口,多出了兩步麻煩的操作。


陳剛 2007-04-06 19:10 發表評論
]]>
Rails學習筆記(2)http://www.tkk7.com/chengang/archive/2007/04/05/108644.html陳剛陳剛Thu, 05 Apr 2007 03:08:00 GMThttp://www.tkk7.com/chengang/archive/2007/04/05/108644.htmlhttp://www.tkk7.com/chengang/comments/108644.htmlhttp://www.tkk7.com/chengang/archive/2007/04/05/108644.html#Feedback2http://www.tkk7.com/chengang/comments/commentRss/108644.htmlhttp://www.tkk7.com/chengang/services/trackbacks/108644.html
《應用Rails...》是好書,翻譯得不錯。不過也有瑕疵,比如書上總出現“引用原書第***頁的***”,暈!難道還要去找原書來翻翻。這種低級錯誤和譯者無關,譯者交書稿時未經過排版,所以是無法確定下頁碼的。而出版商的編輯在排版完成后,本應該交作者再核對修改,但這一道工序似乎被省去了。
 
過去幾年我大都是做后臺,前臺則是用SWT寫胖客戶端。離開WEB已經很久了,WEB的新技術出得很多,AJAX是其中一個比較重要的。買了一本《Ajax基礎教程》看了一章都沒甚么看明白Ajax是個什么樣子,去榕湖圖書館借了本《征服Ajax+Lucene構建搜索引擎》,這回知道什么是Ajax了,其核心很簡單就是XMLHTTPRequest的使用,主要知識面在JavaScript和XML。《征服Ajax...》這書深度不行,注水的內容太多,如果會JavaScript和XML,這本書關于Ajax的近200頁中,只有約20頁的內容對是有用的。現在很多AJAX框架,書中一個都沒講到,看完這本書,你還是無法在實際項目中使用Ajax的,因為自已去寫基礎Javascript代碼太累了,誰還會去重新發明輪子呢?lucene和Ajax沒什么相關技術被糾合在一起寫,不明白作者是怎么想的。如果能把Lucene去掉,加入一些經典AJAX效果的實例,并深入介紹一個較酷的AJAX框架,和一些JavaScript調試開發工具,我想那一定會成為一本極好的書。

去JavaEye查了一下,AJAX的框架很多,讓人不知如何選擇。我看到其中YUI-EXT框架做出來的界面效果相當棒,可以考慮用它。但Rails內置了一些AJAX框架,所以需要以后再比較一下。

YUI-EXT的幾個效果DEMO:
http://extjs.com/deploy/ext/examples/grid/edit-grid.html
http://yui-ext.com/deploy/yui-ext/examples/tree/two-trees.html
http://yui-ext.com/playpen/yui-ext.0.40/examples/dialog/msg-box.html


陳剛 2007-04-05 11:08 發表評論
]]>
Rails學習筆記(1)http://www.tkk7.com/chengang/archive/2007/03/25/106244.html陳剛陳剛Sun, 25 Mar 2007 08:53:00 GMThttp://www.tkk7.com/chengang/archive/2007/03/25/106244.htmlhttp://www.tkk7.com/chengang/comments/106244.htmlhttp://www.tkk7.com/chengang/archive/2007/03/25/106244.html#Feedback0http://www.tkk7.com/chengang/comments/commentRss/106244.htmlhttp://www.tkk7.com/chengang/services/trackbacks/106244.html
我的學習書籍是《應用Rails進行敏捷Web開發》

首先碰到的問題是書中的源代碼下不了,原來給出的網址不讓中國的IP下載(有岐視?),于是用google搜索到?Ruby On Rails 中文社區論壇,找到了源代碼包。地址為(需要注冊登錄到論壇才能看到附件):
http://www.railscn.com/viewtopic.php?t=3258&highlight=%D3%A6%D3%C3Rails%BD%F8%D0%D0%C3%F4%BD%DD
 


P54頁,在創建數據庫時要注意,如果你是才裝的MySQL那么只有一個root用戶,所以不要執行P54頁的grant語句,否則會出錯。grant語句是將數據庫授權給某用戶。而且第三句grant,如把prod改成root后執行,會把root用戶的密碼更改為wibble,導致舊密碼失效,并且網頁執行出“#28000Access denied for user 'root'@'localhost' (using password: YES)”錯誤。所以最好在學習階段就用root用戶得了,三條grant語句都不要執行。當然圖6.1所示的配置文件也改為用root和相應的密碼。



看到P74頁,越來越感覺到開發Rails的速度是如此之快,真是非常簡單方便。但ruby語句比較古靈精怪,我折回到附錄A快速瀏覽了一遍,還是有些地方不太明白。不管這么多先,照貓畫虎把購物車完成先。



陳剛 2007-03-25 16:53 發表評論
]]>
主站蜘蛛池模板: 亚洲小视频在线观看| 国产亚洲一区二区三区在线观看| 四虎影在线永久免费四虎地址8848aa| 免费日本黄色网址| 亚洲无码在线播放| 亚洲理论片中文字幕电影| 亚洲一久久久久久久久| 永久免费观看黄网站| 久久99青青精品免费观看| 亚洲人成网站免费播放| 亚洲成a人无码av波多野按摩| 亚洲精品无码久久一线| 亚洲精品无码久久毛片波多野吉衣| 亚洲欧洲另类春色校园网站| 色吊丝免费观看网站| 日本免费在线观看| 妞干网在线免费观看| 久久亚洲中文字幕精品一区| 亚洲美女视频一区| 女bbbbxxxx另类亚洲| 久久国产免费一区| 拍拍拍又黄又爽无挡视频免费| 久久亚洲精品无码播放| 亚洲乱码在线播放| 日韩在线观看免费完整版视频| 免费人成视频在线观看网站| 日本不卡视频免费| 亚洲AV日韩AV永久无码久久| 亚洲欧美日韩久久精品| 中文无码成人免费视频在线观看 | 国产成人亚洲精品91专区高清| 色播在线永久免费视频网站| 免费在线观看的网站| 国产亚洲成人久久| 国产成人亚洲综合网站不卡| 久久最新免费视频| 妞干网免费视频观看| 亚洲激情在线观看| 日本一区二区三区在线视频观看免费| 国产成人久久AV免费| 亚洲Av无码乱码在线znlu|