a级在线观看,8x国产一区二区三区精品推荐,国产一区二区不卡在线http://www.aygfsteel.com/chengang/category/20990.html    逝者如斯夫不舍晝夜zh-cnTue, 06 Nov 2007 15:40:49 GMTTue, 06 Nov 2007 15:40:49 GMT60VIM的常用插件+配置文件+資料http://www.aygfsteel.com/chengang/archive/2007/10/18/153970.html陳剛陳剛Thu, 18 Oct 2007 10:15:00 GMThttp://www.aygfsteel.com/chengang/archive/2007/10/18/153970.htmlhttp://www.aygfsteel.com/chengang/comments/153970.htmlhttp://www.aygfsteel.com/chengang/archive/2007/10/18/153970.html#Feedback6http://www.aygfsteel.com/chengang/comments/commentRss/153970.htmlhttp://www.aygfsteel.com/chengang/services/trackbacks/153970.html 我把VIM的常用插件,自己用的配置文件,收羅的一些資料一并打包了,省得初用VIM的人找來找去浪費(fèi)時(shí)間。

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



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


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

剩下的重點(diǎn)就是怎么定義配置文件。首先是要?jiǎng)澢迮渲梦募呢?zé)任界線----它只負(fù)責(zé)定義盒子里的數(shù)據(jù),還有盒子的嵌套關(guān)系,而大小和位置等布局方面則全部交給CSS去負(fù)責(zé)。

上面是初步想法,下面看看具體實(shí)現(xiàn),代碼僅供參考

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

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

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里把配置文件讀入,再轉(zhuǎn)化成模型類。我把各個(gè)界面模塊看做一個(gè)個(gè)盒子Box
這是它的頂級(jí)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子類大同小異

然后在一個(gè)controller里把這些配置信息轉(zhuǎn)成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%>?
?

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


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

1. 新增兩個(gè)javascript函數(shù)。
var?currentImageTextID;

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

//imageTextID:?圖片文本框的ID值
//
uploadPath:?服務(wù)器的圖片目錄
//
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中這樣使用
標(biāo)志圖片:
<
input?id="topic_image"?name="topic[image]"?size="30"?type="text">
<
input?value="瀏覽服務(wù)器"?onclick="OpenImageBrowser('topic_image',?'/uploads/s<%= params[:user_id]%>',?'Image')"?type="button">




陳剛 2007-09-26 18:49 發(fā)表評(píng)論
]]>
讓Rails版的FCKEditor支持動(dòng)態(tài)設(shè)置上傳目錄http://www.aygfsteel.com/chengang/archive/2007/09/26/148114.html陳剛陳剛Wed, 26 Sep 2007 02:13:00 GMThttp://www.aygfsteel.com/chengang/archive/2007/09/26/148114.htmlhttp://www.aygfsteel.com/chengang/comments/148114.htmlhttp://www.aygfsteel.com/chengang/archive/2007/09/26/148114.html#Feedback3http://www.aygfsteel.com/chengang/comments/commentRss/148114.htmlhttp://www.aygfsteel.com/chengang/services/trackbacks/148114.html
文/陳剛 www.chengang.com.cn 轉(zhuǎn)載請(qǐng)保留出處
1.修改fckeditor_controller.rb,把它那幾個(gè)private方法修改如下:
??
??
private
??def?current_directory_path
????base_dir?
=?"#{RAILS_ROOT}/public"

????#TODO?在創(chuàng)建用戶時(shí),就建立好目錄。這時(shí)可以去掉這部份代碼,提高運(yùn)行效率。
????(
"#{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]是關(guān)鍵,它就是我們動(dòng)態(tài)定義的上傳目錄。該值來自于FCKEditor的一些html頁面,它是通過get參數(shù)傳入的。修改browser.html文件(如下粗體部份),在它的url請(qǐng)求中把我們定義目錄加入到get參數(shù)列中,這樣它就可以傳到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參數(shù)列中。

//?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(這兩個(gè)文件對(duì)javascript進(jìn)行了壓縮處理,修改起來較難操作)。我是參考了oFCKeditor.Config['CustomConfigurationsPath'] 這個(gè)參數(shù)的載入實(shí)現(xiàn),才找到這種鳥不生蛋的地方。搜索這兩個(gè)文件的關(guān)鍵字CustomConfigurationsPath,找到如下一行,然后加入一個(gè)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]}來自于我們前臺(tái)的view了。如下粗體所示,把標(biāo)準(zhǔn)的fckeditor_textarea新增加了一個(gè)參數(shù),其中params[:user_id]是把用戶的ID值做為目錄名。這樣就實(shí)現(xiàn)了動(dòng)態(tài)改變FCKEditor的上傳目錄。

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


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


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

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


1.中文化

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

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

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








陳剛 2007-09-24 18:24 發(fā)表評(píng)論
]]>
error_messages_for的中文化http://www.aygfsteel.com/chengang/archive/2007/09/19/146548.html陳剛陳剛Wed, 19 Sep 2007 09:35:00 GMThttp://www.aygfsteel.com/chengang/archive/2007/09/19/146548.htmlhttp://www.aygfsteel.com/chengang/comments/146548.htmlhttp://www.aygfsteel.com/chengang/archive/2007/09/19/146548.html#Feedback0http://www.aygfsteel.com/chengang/comments/commentRss/146548.htmlhttp://www.aygfsteel.com/chengang/services/trackbacks/146548.htmlApplicationHelper
文/陳剛? www.chengang.com.cn? 轉(zhuǎn)載請(qǐng)聲明出處

? 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}個(gè)錯(cuò)誤"
#???????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


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

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

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



陳剛 2007-09-19 17:35 發(fā)表評(píng)論
]]>
讓will_paginate的分頁支持ajaxhttp://www.aygfsteel.com/chengang/archive/2007/09/02/142077.html陳剛陳剛Sun, 02 Sep 2007 07:42:00 GMThttp://www.aygfsteel.com/chengang/archive/2007/09/02/142077.htmlhttp://www.aygfsteel.com/chengang/comments/142077.htmlhttp://www.aygfsteel.com/chengang/archive/2007/09/02/142077.html#Feedback7http://www.aygfsteel.com/chengang/comments/commentRss/142077.htmlhttp://www.aygfsteel.com/chengang/services/trackbacks/142077.html
文/陳剛 (www.chengang.com.cn)
但一直搜不到它支持ajax分面的方法 ,于是我參考它分頁方法的源代碼(位于:vendor/plugins/will_paginate/lib/will_paginate/view_helpers.rb),稍微改寫,變成了一個(gè)支持ajax的分頁方法。以下代碼復(fù)制到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的后綴,主要是為了補(bǔ)全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 發(fā)表評(píng)論
]]>
在Rails中使用FCKeditor插件實(shí)現(xiàn)WEB富文本編輯http://www.aygfsteel.com/chengang/archive/2007/08/25/139287.html陳剛陳剛Sat, 25 Aug 2007 08:44:00 GMThttp://www.aygfsteel.com/chengang/archive/2007/08/25/139287.htmlhttp://www.aygfsteel.com/chengang/comments/139287.htmlhttp://www.aygfsteel.com/chengang/archive/2007/08/25/139287.html#Feedback0http://www.aygfsteel.com/chengang/comments/commentRss/139287.htmlhttp://www.aygfsteel.com/chengang/services/trackbacks/139287.html
文/陳剛? (www.chengang.com.cn)

環(huán)境:ubuntu linux 7.0.4? +? ruby 1.8.5 + Rails 1.2.3 + FCKeditor 0.4.1

直接從它的subversion庫(kù)里取得該Rails插件。先進(jìn)入到你的項(xiàng)目根目錄,再執(zhí)行如下命令
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安裝在項(xiàng)目根目錄下的vendor/plugins/fckeditor 里,
(5)vendor/plugins/fckeditor里的README很值得一讀,我碰到Ajax問題,查了所以網(wǎng)上的中文資料都沒有提到,在這個(gè)README卻有。


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

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


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

說明:topic對(duì)應(yīng)模型對(duì)象,content對(duì)應(yīng)它的字段。也就是要求當(dāng)前頁要有@topic這個(gè)實(shí)例變量。


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

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





在使上傳圖片的功能時(shí)碰到了錯(cuò)誤。彈出出alert對(duì)話框,顯示: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找到了答案,這是一個(gè)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 發(fā)表評(píng)論
]]>
mootools VS prototypehttp://www.aygfsteel.com/chengang/archive/2007/08/23/138780.html陳剛陳剛Thu, 23 Aug 2007 04:11:00 GMThttp://www.aygfsteel.com/chengang/archive/2007/08/23/138780.htmlhttp://www.aygfsteel.com/chengang/comments/138780.htmlhttp://www.aygfsteel.com/chengang/archive/2007/08/23/138780.html#Feedback0http://www.aygfsteel.com/chengang/comments/commentRss/138780.htmlhttp://www.aygfsteel.com/chengang/services/trackbacks/138780.html前天為了實(shí)現(xiàn)一個(gè)Lightbox的效果,搜了一些資料,引出了mootools這一個(gè)javascript庫(kù)(http://mootools.net/ )。其效果的確很酷,這個(gè)是它的常見效果實(shí)現(xiàn)一覽表http://demos.mootools.net/

我覺得mootools比prototype強(qiáng)的地方,就是它的理念更OO,重點(diǎn)表現(xiàn)在它把javascript、html、css完全分離開來,用mootools的話,html里干凈得找不到j(luò)avascript的影子。javascript、html 分離,這很重要。

其次 ,mootools的文檔很不錯(cuò),在http://demos.mootools.net/ 這個(gè)效果一覽表中,你可以很輕松的看到實(shí)現(xiàn)效果的代碼。代碼清晰的分為三個(gè)部份javascript、html、css,你只要將這些代碼復(fù)制到你的項(xiàng)目中就能得到預(yù)期的效果。它的javascript代碼對(duì)于有java或OO基礎(chǔ)的人相當(dāng)易懂。


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


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





陳剛 2007-08-23 12:11 發(fā)表評(píng)論
]]>
Rails驗(yàn)證碼圖片的實(shí)現(xiàn)http://www.aygfsteel.com/chengang/archive/2007/08/17/137683.html陳剛陳剛Fri, 17 Aug 2007 11:48:00 GMThttp://www.aygfsteel.com/chengang/archive/2007/08/17/137683.htmlhttp://www.aygfsteel.com/chengang/comments/137683.htmlhttp://www.aygfsteel.com/chengang/archive/2007/08/17/137683.html#Feedback0http://www.aygfsteel.com/chengang/comments/commentRss/137683.htmlhttp://www.aygfsteel.com/chengang/services/trackbacks/137683.html
在linux下生成圖片需要圖片處理軟件ImageMagick的Ruby語言RMagick庫(kù)支持。安裝RMagick最麻煩,我查了N多資料試了N次才安裝成功。
   1. 安裝ImageMagick:sudo apt-get install imagemagick
   2. 查看安裝結(jié)果: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. 說明:如果出現(xiàn)問題或者錯(cuò)誤請(qǐng)執(zhí)行下面命令:sudo apt-get remove --purge libmagick9-dev

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

第二步:編碼

在models目錄創(chuàng)建一個(gè)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') #圖片位于項(xiàng)目根目錄下。也可以使用linux中的絕對(duì)路徑如:
/home/chengang/test.gif

  end
end


在一個(gè)controller里加入一個(gè)方法,方法的作用是向網(wǎng)頁提供圖片數(shù)據(jù)。我選擇創(chuàng)建一個(gè)專門的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


以下是在頁面中的調(diào)用代碼:

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


其中changeImage()是一個(gè)javascript函數(shù),因?yàn)閾Q圖片時(shí)必須改變<img的src,否則瀏覽器不會(huì)執(zhí)行UtilController的proof_image方法,而是從緩存中取得圖片數(shù)據(jù)。

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


我的環(huán)境:ubuntu 7.04 + Rails 1.2.3 +Ruby 1.8.5



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

我學(xué)習(xí)REST的途徑如下:

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

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

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

看完<RESTful Rails Development>就可以開始對(duì)自己的網(wǎng)站重構(gòu)了,有不懂的地方再參考一下別人beast是怎么實(shí)現(xiàn)的。




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

書分四大部份,第一部分講語法基礎(chǔ),這部分是需要認(rèn)真讀的。這部份寫得很細(xì),很不錯(cuò),需要認(rèn)真做一些筆記。

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

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

第四部分是枯燥的API參考,也是需要重點(diǎn)了解熟悉的,不清楚API還編個(gè)什么勁。不過對(duì)于英文版的讀者來說,這似乎完全沒有必要,因?yàn)榫W(wǎng)上有最新API文檔可查閱,內(nèi)容基本是一樣的。當(dāng)然對(duì)于國(guó)內(nèi)讀者來說,這部份翻譯成中文還是有價(jià)值的,免去了讀英文API文檔的痛苦。

如果你有JAVA的基礎(chǔ),書的前三部份可以在四天內(nèi)讀完。不過我覺得第一部份應(yīng)該多看幾遍,而第四部份也需經(jīng)常通讀,今后編程會(huì)常常翻查API。 總的來說,這本書對(duì)于學(xué)習(xí)Ruby還是很有用的,關(guān)鍵是翻譯得也還不錯(cuò),讀起來牙不酸胃不痛,所以值得一買。








陳剛 2007-08-08 09:01 發(fā)表評(píng)論
]]>
用AJAX實(shí)現(xiàn)氣泡提示http://www.aygfsteel.com/chengang/archive/2007/07/31/133508.html陳剛陳剛Tue, 31 Jul 2007 07:32:00 GMThttp://www.aygfsteel.com/chengang/archive/2007/07/31/133508.htmlhttp://www.aygfsteel.com/chengang/comments/133508.htmlhttp://www.aygfsteel.com/chengang/archive/2007/07/31/133508.html#Feedback6http://www.aygfsteel.com/chengang/comments/commentRss/133508.htmlhttp://www.aygfsteel.com/chengang/services/trackbacks/133508.html                                    文/陳剛 www.chengang.com.cn (轉(zhuǎn)載請(qǐng)注明)

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

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.aygfsteel.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的代碼(涉及到的相關(guān)圖片: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;
    }

然后給需要?dú)馀萏崾镜募由鲜髽?biāo)事件:
 <span class="l1" onmouseover="Element.show('content_<%=o.id%>')" onmouseout="Element.hide('content_<%=o.id%>')"><%=article_link_to(o.title,o.id)%></span>



二、繼續(xù)改進(jìn)
氣泡提示的外圍HTML表格代碼可以改由javascript來動(dòng)態(tài)生成,這樣可以縮小一些頁面的總HTML大小。

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


然后給需要?dú)馀萏崾镜募由鲜髽?biāo)事件。
    <span class="l1" onmouseover="showPopup('content_<%=o.id%>',event);" onmouseout="hidePopup()"><%=article_link_to(o.title,o.id)%></span>

CSS的代碼不變。

寫兩個(gè)javascript函數(shù):
function showPopup(element_id,event){
  
var div = createElement("div");  
  div.id 
= "popup";
  
//div.style.display="none";
  var popup = $(element_id);
  
//取得鼠標(biāo)的絕對(duì)坐標(biāo)
  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有一點(diǎn)問題,所以就沒再用。

效果如下圖所示:








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

但如果使用ajax則分頁的實(shí)現(xiàn)需要改動(dòng)一下,如下所示。

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


然后再優(yōu)化一下,把這些代碼提取成一個(gè)公共函數(shù),放在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 發(fā)表評(píng)論
]]>
[遷移到Linux] 遷移mysqlhttp://www.aygfsteel.com/chengang/archive/2007/06/12/123491.html陳剛陳剛Mon, 11 Jun 2007 16:33:00 GMThttp://www.aygfsteel.com/chengang/archive/2007/06/12/123491.htmlhttp://www.aygfsteel.com/chengang/comments/123491.htmlhttp://www.aygfsteel.com/chengang/archive/2007/06/12/123491.html#Feedback2http://www.aygfsteel.com/chengang/comments/commentRss/123491.htmlhttp://www.aygfsteel.com/chengang/services/trackbacks/123491.html  最近這段時(shí)間關(guān)于版權(quán)的問題,越來越重視了,已經(jīng)成為國(guó)與國(guó)之間的大事,必竟這關(guān)系于一大筆$。雖然,我的XP是正版的,但還是考慮遷移到linux上來,并把linux做為今后的工作環(huán)境。咱也要爭(zhēng)口氣,說我盜版,那我不用你的不就成了。我選用的linux版本是ubuntu 7.04,這篇博客就是在新操作系統(tǒng)上寫的。


遷移動(dòng)linux上還是碰到了不少問題,主要還是習(xí)慣的問題。雖然ubuntu的桌面環(huán)境已經(jīng)非常不錯(cuò)了,但很多編程方面的軟件還是命令行式的,比如mysql。




安裝MySQL



sudo apt-get install mysql-server mysql-client


root原密碼為空,給它加個(gè)密碼

mysqladmin -uroot -password 123456


導(dǎo)入SQL腳本

mysql -uroot -p123456 < db/create_table.sql


重啟動(dòng)mysql服務(wù)
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


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

SET NAMES 'utf8';




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



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



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





陳剛 2007-05-13 00:46 發(fā)表評(píng)論
]]>
Rails學(xué)習(xí)筆記(7)實(shí)現(xiàn)分頁,及數(shù)據(jù)庫(kù)模型命名限制http://www.aygfsteel.com/chengang/archive/2007/05/08/116053.html陳剛陳剛Tue, 08 May 2007 14:09:00 GMThttp://www.aygfsteel.com/chengang/archive/2007/05/08/116053.htmlhttp://www.aygfsteel.com/chengang/comments/116053.htmlhttp://www.aygfsteel.com/chengang/archive/2007/05/08/116053.html#Feedback0http://www.aygfsteel.com/chengang/comments/commentRss/116053.htmlhttp://www.aygfsteel.com/chengang/services/trackbacks/116053.html
先在Action使用paginate方法,如下。
其中得到的數(shù)據(jù)記錄會(huì)在@articles變量里,頁的信息在@article_pages變量里。
paginate方法的第一參數(shù)是數(shù)據(jù)表名,order_by根據(jù)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)%>

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


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

今天還碰到一個(gè)問題,我把表titles改名為modules后,模型文件名為module.rb,其他部份也做了修改。運(yùn)行后出了錯(cuò),出錯(cuò)信息是Module.class沒有find方法(我在action調(diào)用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


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




陳剛 2007-05-08 22:09 發(fā)表評(píng)論
]]>
XHTML+CSS (2) 一個(gè)通用頁面框架http://www.aygfsteel.com/chengang/archive/2007/04/19/111895.html陳剛陳剛Thu, 19 Apr 2007 05:22:00 GMThttp://www.aygfsteel.com/chengang/archive/2007/04/19/111895.htmlhttp://www.aygfsteel.com/chengang/comments/111895.htmlhttp://www.aygfsteel.com/chengang/archive/2007/04/19/111895.html#Feedback0http://www.aygfsteel.com/chengang/comments/commentRss/111895.htmlhttp://www.aygfsteel.com/chengang/services/trackbacks/111895.html每個(gè)頁面都可以用的XHTML模板(擴(kuò)展點(diǎn)為*.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>
       。。。。。。。。主頁內(nèi)容
</body>
</html>

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

我也簡(jiǎn)單用DIV+CSS寫了一個(gè)簡(jiǎn)單的頁面框架:http://www.aygfsteel.com/Files/chengang/xhtml_css_demo.rar。這個(gè)DEMO在IE7下顯示正常,在FireFox3下則有點(diǎn)問題。但用Amaya檢查,沒有發(fā)現(xiàn)格式錯(cuò)誤。有高手懂的幫指出一下。

補(bǔ):
li列表在FF3下顯示出圓點(diǎn)的解決,加式樣:list-style:none;


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

錯(cuò)誤現(xiàn)象:
。用MySQL Query Browser查看MySQL數(shù)據(jù),中文顯示正常。
。頁面顯示為亂碼,原來是中文的地方都變成了一個(gè)長(zhǎng)方塊
。手工調(diào)整瀏覽器的頁面編碼,可以使用頁面正常顯示。但刷新后又是亂碼。

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

 

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

 

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


注:

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


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


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

 

4。有的人說在建表的時(shí)候不能用InnoDB,但我的建表語句如下,是用InnoDB。沒有發(fā)現(xiàn)問題。

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 發(fā)表評(píng)論
]]>
Rails學(xué)習(xí)筆記(5)第6、7、8章摘要http://www.aygfsteel.com/chengang/archive/2007/04/10/109408.html陳剛陳剛Tue, 10 Apr 2007 01:47:00 GMThttp://www.aygfsteel.com/chengang/archive/2007/04/10/109408.htmlhttp://www.aygfsteel.com/chengang/comments/109408.htmlhttp://www.aygfsteel.com/chengang/archive/2007/04/10/109408.html#Feedback0http://www.aygfsteel.com/chengang/comments/commentRss/109408.htmlhttp://www.aygfsteel.com/chengang/services/trackbacks/109408.html
執(zhí)行SQL腳本:mysql depot_development < db/create.sql
創(chuàng)建三個(gè)庫(kù),分別用于開發(fā)、測(cè)試、生產(chǎn):depot_development、depot_test、depot_production。
每個(gè)表都應(yīng)該帶一個(gè)和業(yè)務(wù)無關(guān)的ID字段。
在rails配置數(shù)據(jù)庫(kù)的連接:config\database.yml。密碼之前冒號(hào)之后要間隔一個(gè)空格。

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


啟動(dòng)WEB服務(wù):ruby script/server。(http://localhost:3000/admin


模型類:
。validates_presence_of  :title, :desc, :image_url   必須不為空
。validates_numericality_of :price  必須是數(shù)字
。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"  文件名必須是圖片文件的擴(kuò)展名
。模型保存到數(shù)據(jù)庫(kù)之前會(huì)調(diào)用validate方法,例:
  def validate
    errors.add(:price, 
"should be positive") unless price.nil? || price > 0.0
  end



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


以下為鏈接,效果相當(dāng)于以前的“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)  顯示產(chǎn)品描述字段的摘要(80個(gè)字符)
product.date_available.strftime("%y-%m-%d") 日期字段的格式化顯示
sprintf("%0.2f", product.price) 數(shù)值的格式化顯示, number_to_currency方法也有類似功能

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


布局模板
。app/views/layouts目錄中創(chuàng)建一個(gè)與控制器同名的模板文件store.rhtml,則控制器下所有網(wǎng)頁都會(huì)使用此模板

 

<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兩個(gè)式樣表的<link>標(biāo)簽
@page_title 各個(gè)頁面標(biāo)題變量
@flash[:notice] 提示性的信息(key=notice),這是一個(gè)公共變量。
。<%= @content_for_layout %> 位置嵌入顯示控制器內(nèi)名網(wǎng)頁。由于其他網(wǎng)頁變成了模板的一部份,所以其<html>等標(biāo)簽應(yīng)該去掉。



store_controller.rb ,當(dāng)從session里取出某購(gòu)物車不存在,則新建一個(gè),并存入session。最后把此購(gòu)物車賦給變量cart。

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


ruby  script/generate  model  LineItem,創(chuàng)建一個(gè)LineItem的數(shù)據(jù)模型,附帶還會(huì)創(chuàng)建相應(yīng)的測(cè)試程序。

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的參數(shù)數(shù)組
。redirect_to轉(zhuǎn)向語句
。rescue 異常,相當(dāng)于Java的Exception
。redirect_to_index是application.rb中的一個(gè)方法,這個(gè)文件里的方法是各控制器公開的。
。logger是rails內(nèi)置的變量。

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沒有對(duì)應(yīng)的數(shù)據(jù)表,它只是一個(gè)普通的數(shù)據(jù)類,因此要定義相應(yīng)的屬性。
。@items << item 把對(duì)象item加入到@items數(shù)組
。@items=[]   空數(shù)組


如果出現(xiàn)SessionRestoreError錯(cuò)誤,則檢查application.rb是否做了如下的模型聲明。因?yàn)閷?duì)于動(dòng)態(tài)語句,session把序列化的類取出時(shí),否則是無法知道對(duì)象類型的,除非聲明一下。

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


<%  ... -%>  -%>相當(dāng)于一個(gè)換行符


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


if @items.empty?   判斷數(shù)組是否為空數(shù)組

flash[:notice] flash可以在同一個(gè)Session的下一個(gè)請(qǐng)求中使用,隨后這些內(nèi)容就會(huì)被自動(dòng)刪除(下一個(gè)的下一個(gè)就被清空了??)。
實(shí)例變量是代替不了flash的,因?yàn)镮E無狀態(tài)的特性,在下一個(gè)請(qǐng)求中,上一個(gè)請(qǐng)求的實(shí)例變量已失效。


當(dāng)異常沒有被任何程序捕捉,最后總會(huì)轉(zhuǎn)到ApplicationController的rescue_action_in_public()方法


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

 



陳剛 2007-04-10 09:47 發(fā)表評(píng)論
]]>
Rails學(xué)習(xí)筆記(4)數(shù)據(jù)庫(kù)配置及頁面讀取http://www.aygfsteel.com/chengang/archive/2007/04/09/109255.html陳剛陳剛Mon, 09 Apr 2007 06:36:00 GMThttp://www.aygfsteel.com/chengang/archive/2007/04/09/109255.htmlhttp://www.aygfsteel.com/chengang/comments/109255.htmlhttp://www.aygfsteel.com/chengang/archive/2007/04/09/109255.html#Feedback0http://www.aygfsteel.com/chengang/comments/commentRss/109255.htmlhttp://www.aygfsteel.com/chengang/services/trackbacks/109255.html開始在MySQL中創(chuàng)建數(shù)據(jù)庫(kù),分別用于:開發(fā)、測(cè)試、產(chǎn)品

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

在開發(fā)庫(kù)中建表和插入數(shù)據(jù):
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,'關(guān)于','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;

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

# 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

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

創(chuàng)建視圖: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變量來自于我們自己創(chuàng)建的如下控制器: app\controllers\homepage_controller.rb。Rails中控制器中的變量可以在視圖中使用(這是否會(huì)產(chǎn)生變量污染的問題呢,還待以后再體驗(yàn))

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

最后啟動(dòng)Web服務(wù)器后訪問:http://localhost:3000/homepage 

 



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

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


Mongrel是WEB服務(wù)器,這里可不設(shè)置。一般是用Apache做前端請(qǐng)求轉(zhuǎn)發(fā),后端用mongrel做集群,以實(shí)現(xiàn)大負(fù)荷訪問。




在Eclipse右下角的Server視圖可以啟動(dòng)WEB服務(wù)器。
創(chuàng)建一個(gè)Controller,在書中是這個(gè)命令:ruby script/generate controller say
Eclipse中的方式則如下圖所示:


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


創(chuàng)建一個(gè)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循環(huán)到1 (32、1共三次循環(huán))
      puts count
      puts 
"#{count} " + @blogsite
    end
    
  end
end

hello相當(dāng)于一個(gè)Action,不過要顯示W(wǎng)EB頁面(http://localhost:3000/say/hello )還需要在一個(gè)rhtml文件:views/say/hello.rhtml

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

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

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

1.hour.from_now 從現(xiàn)在過去1小時(shí)后的時(shí)間。數(shù)字也是一個(gè)對(duì)象,也具有方法。

3.times do  #三次循環(huán)
  puts 
"chengang"
end


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


<%= link_to "bye bye", :action=>"goodbye"%> 一個(gè)指向當(dāng)前控制器say的goodbye這個(gè)Action的鏈接


---------------------------------------
www.aygfsteel.com對(duì)FirFox支持不太好,在編輯文章復(fù)制粘貼時(shí),平白彈出一個(gè)窗口,多出了兩步麻煩的操作。


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

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

YUI-EXT的幾個(gè)效果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 發(fā)表評(píng)論
]]>
Rails學(xué)習(xí)筆記(1)http://www.aygfsteel.com/chengang/archive/2007/03/25/106244.html陳剛陳剛Sun, 25 Mar 2007 08:53:00 GMThttp://www.aygfsteel.com/chengang/archive/2007/03/25/106244.htmlhttp://www.aygfsteel.com/chengang/comments/106244.htmlhttp://www.aygfsteel.com/chengang/archive/2007/03/25/106244.html#Feedback0http://www.aygfsteel.com/chengang/comments/commentRss/106244.htmlhttp://www.aygfsteel.com/chengang/services/trackbacks/106244.html
我的學(xué)習(xí)書籍是《應(yīng)用Rails進(jìn)行敏捷Web開發(fā)》

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


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



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



陳剛 2007-03-25 16:53 發(fā)表評(píng)論
]]>
主站蜘蛛池模板: 大关县| 临朐县| 绥棱县| 会理县| 辰溪县| 宁城县| 宁津县| 平罗县| 阳新县| 武山县| 富锦市| 遂川县| 九寨沟县| 乐都县| 边坝县| 景宁| 弥渡县| 大宁县| 木里| 门头沟区| 谢通门县| 百色市| 清远市| 鄢陵县| 文化| 尼玛县| 铜山县| 怀安县| 越西县| 萝北县| 赤峰市| 临武县| 辽宁省| 阿拉善左旗| 阳高县| 合江县| 宽城| 桦甸市| 锡林浩特市| 乐山市| 天柱县|