Rails-sanitize()方法

sanitize()方法接收包含HTML的字符串作为参数,并清除其中危险的元素.< form>和< script>标签都会被转义,on=属性和javascript:字样开头的链接都会被直接删除.
VIEW模板中常用的h()方法原来是html_escape()的缩写.^_^

学习Base64编码

Base64是一种编码方法, 它只使用ASCII码中的65个字符(包括[A-Za-z0-9+/]这64字符和用来padding的'='),且最多只会在末尾出现两个'='。将3个8位字节(8bits * 3 = 24bits)中的二进制代码转为4个6位的字节(6bits * 4 = 24bits),之后在6位的前面补两个0,形成8位一个字节的形式。具体详情参考这里。被base64编码过的字符串。每隔60个8位字节(或在结尾)添加一个换行代码。
Ruby的Array类中的pack('m'),unpack('m')方法就是用来干这个的,分别对应编码,解码.
顺便提一下,Rails中将图片等存入数据库中时,需要使用pack('m')方法,将其转换为数据库能够接受的Base64编码方式.比如可以这样来实现.

module ToBaseData
def self.load(filename)
data = File.open(filename, 'rb').read
"!binary | #{[data].pack('m').gsub(/\n/, "\n ")}\n"
end
end

Rails-Time#to_s(:format)


# >> Time.now.to_s(:time)
# => "01:50"
# >> Time.now.to_s(:short)
# => "Dec 18, 2006"
# >> Time.now.to_s(:db)
# => "2006-12-18 01:50:42"
# >> time.to_s(:stamp)
# => 5:23PM
# >> time.to_s(:relative)
# => today

Rails统一出错页面

Rails在出错的时候会调用../actionpack/lib/action_controller/rescue.rb中的rescue_action(exception) ,只要在application.rb覆写该函数就行了,看看这个函数的源码.

protected
# Exception handler called when the performance of an action raises an exception.
def rescue_action(exception)
log_error(exception) if logger
erase_results if performed?

# Let the exception alter the response if it wants.
# For example, MethodNotAllowed sets the Allow header.
if exception.respond_to?(:handle_response!)
exception.handle_response!(response)
end

if consider_all_requests_local || local_request?
rescue_action_locally(exception)
else
rescue_action_in_public(exception)
end
end

注意最后面的IF语句,判断request是否来自本地的请求,如果是development,exception将由rescue_action_locally方法进行处理,否则由rescue_action_in_public方法处理.如下,将出错页面定向到自定义的页面.

def rescue_action(exception)
log_error(exception) if logger
erase_results if performed?

# Let the exception alter the response if it wants.
# For example, MethodNotAllowed sets the Allow header.
if exception.respond_to?(:handle_response!)
exception.handle_response!(response)
end

if consider_all_requests_local || local_request?
render :file => "#{RAILS_ROOT}/public/dev_error.html.erb"
else
render :file => "#{RAILS_ROOT}/public/pub_error.html.erb"
end
end

Rails国际化

1.$KCODE
Ruby中,文字编码的设定是通过全局变量$KCODE来进行,没有对编码方式进行正确的话,有可能会出现乱码的问题.要进行$KCODE设定的话,可以在config/environment文件的前面加上

$KCODE = "UTF8"

这里假设进行UTF-8的设定,如果没有特殊要求的话,推荐使用UTF-8.特别是利用AJAX的时候,UTF-8是必须的.

2.charset参数
为了在浏览器中正确显示文字,那么对Content-Type中charset参数的设定就是必要的了.这个参数除了在VIEW文件中可以设定,在controller文件中也同样可以设定.为了不重复代码,推荐在app/controllers/application.rb中的ApplicationController里进行设置,方法如下.

class ApplicationController < ActionController::Base
before_filter :set_charset

private
def set_charset
headers["Content-Type"] = "text/html;charset=UTF-8"
end

3.数据库的设定
文字无乱码的存入数据库,以及从数据库中取出来,那么就必须对数据库以及database.yml文件的编码方式进行设定了.
MySQL中,数据库创建时可以进行编码方式的指定.如

create database pro_development default character set utf8;

PostgreSQL中也一样可以进行设定,如

createdb --encoding UTF8 pro_development

另外配置文件的设定,在database.yml中指定encoding.如

development:
adapter: sqlite3
database: dum_development
timeout: 5000
encoding: utf8

VIM大小写的变换

guw (光标到词尾,大写转换成小写)
gUw (光标到词尾,小写转换成大写)

guu (光标到行尾,大写转换成小写)
gUU (光标到行尾,小写转换成大写)

~ (单个字符大写转小写,小写转大写)
个数 + "~" (大写转小写,小写转大写)

guG (光标到文件未,大写转换成小写)
gUG (光标到文件未,小写转换成大写)

ASP防SQL注入

在网上看到一个ASP防SQL注入的方法,感觉不错.

Function SafeRequest(ParaName)
Dim ParaValue
ParaValue=Request(ParaName)
if IsNumeric(ParaValue) = True then
SafeRequest=ParaValue
exit Function
elseIf
Instr(LCase(ParaValue),"select ") > 0 or Instr(LCase(ParaValue),"insert ") > 0 or Instr(LCase(ParaValue),"delete from") > 0 or Instr(LCase(ParaValue),"count(") > 0 or Instr(LCase(ParaValue),"drop table") > 0 or Instr(LCase(ParaValue),"update ") > 0 or Instr(LCase(ParaValue),"truncate ") > 0 or Instr(LCase(ParaValue),"asc(") > 0 or Instr(LCase(ParaValue),"mid(") > 0 or Instr(LCase(ParaValue),"char(") > 0 or Instr(LCase(ParaValue),"xp_cmdshell") > 0 or Instr(LCase(ParaValue),"exec master") > 0 or Instr(LCase(ParaValue),"net localgroup administrators") > 0 or Instr(LCase(ParaValue)," and ") > 0 or Instr(LCase(ParaValue),"net user") > 0 or Instr(LCase(ParaValue)," or ") > 0 then
Response.Write "<script language='javascript'>"
Response.Write "alert('非法的请求!');" '发现SQL注入攻击提示信息
Response.Write "location.href='./error.html';" '发现SQL注入攻击转跳网址
Response.Write "<script>"
Response.end
else
SafeRequest=ParaValue
End If
End function

使用SafeRequest函数替换Request

Ruby CGI + jquery -第一个HelloWorld

今天用Ruby CGI写了第一个小程序,其中也尝试了一下传说中的Jquery,感觉确实不错.其中有一些小技巧,为了不忘记特记录于此.
第一个文件(bbs.cgi):

#!/ruby/bin/ruby -Ks
require "cgi"

bbsfile = open("bbs.dat","r")
mes = CGI.escapeHTML(bbsfile.read)
bbsfile.close

print "Content-type:text/html\n\n"

print <<EOF
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=Shift_JIS">
<script src="jquery.js" type="text/javascript"></script>
<title>掲示板</title>
<script type="text/javascript">
$(document).ready(function(){
$("input[name='s']").click(function(){
if($("input[name='name']").val()==""){
alert("please input your name!");
$("input[name='name']").css({backgroundColor:"yellow",fontWeight:"bolder",border:"3px solid red"});
return false;
}
else if($("input[name='text']").val()==""){
alert("please input message!");
$("input[name='text']").css({backgroundColor:"yellow",fontWeight:"bolder",border:"3px solid red"});
return false;
}
});
$("input[name='name']").keyup(function(){
$("input[name='name']").css({backgroundColor:"",fontWeight:"",border:""});
});
$("input[name='text']").keyup(function(){
$("input[name='text']").css();
});
$("input[type='reset']").click(function(){
$("input[name='name']").css();
$("input[name='text']").css();
});
$("a").click(function(){
$("pre").slideToggle("fast");
});
});
</script>
</head>
<body>
EOF

print <<EOF
<form action="./up.cgi" method="get">
</center>
<h2>簡単な掲示板</h2>
メッセージをどうぞ<br><br>
<table border=0>
<tr><td>メッセージ:<td><input name="text" value="" size=50></tr>
<tr><td>お名前:<td><input name="name" value=""></tr>
<tr><td></td><td><input type="submit" name="s" value="書き込む">
<input type="reset" value="クリア"></tr>
</table>
</form>
<hr>
EOF

print <<EOF
<!--<input type="button" name="msg" value="Message">-->
<a href="#" style="text-decoration:none">>>Message</a>
<pre>
<del>
#{mes}
</del>
</pre>
EOF

print <<EOF
</body>
</html>
EOF

第二个文件(up.cgi):

#!/ruby/bin/ruby -Ks
require "cgi"

cgi=CGI.new
message=cgi["text"]
name=cgi["name"]

bbsfile=open("bbs.dat","a")
bbsfile.write(name + ": " +message+"\n")
bbsfile.close

print "Content-type:text/html\n\n"

print <<EOF
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=shift_JIS">
<title>form</title>
</head>

<body>
書き込みありがとうございました。<br><br>
<a href="bbs.cgi">return></a>
</body>
</html>
EOF

[Rails]去除错误产生时输入框的显示效果

Rails中当错误发生时,会用红线将出错的入力框框起来,突出显示,如果不需要这种显示效果,可以将其去掉.在/controllers/application.rb中加入如下代码:

ActionView::Base.field_error_proc = Proc.new{|snippet,instance|"#{snippet}"}

如果想更改显示样式,也以同样的方法进行修改,比如下面的代码,将出错的输入框的背景色改为银色,以突出显示.

ActionView::Base.field_error_proc = Proc.new do |html_tag, instance|
msg = instance.error_message
error_style = "background-color: #ececec"
if html_tag =~ /<(input|textarea|select)[^>]+style=/
style_attribute = html_tag =~ /style=['"]/
html_tag.insert(style_attribute + 7, "#{error_style}; ")
elsif html_tag =~ /<(input|textarea|select)/
first_whitespace = html_tag =~ /\s/
html_tag[first_whitespace] = " style='#{error_style}' "
end
html_tag
end

Rails2.0向数据库添加字段文件命名的问题

今天在继续Rails2.0的WEB开发时,忽然想往已经定义好的用户主表Users中添加一个email字段,这对于ROR来说当然很好解决了,一句"ruby script/generate migration addemailtousers email:string"就行了,但当打开migrate文件时却发现没有"add_column :admins, :email, :string",也就说migration没理解我的意思.Google上搜索了一下也没找到相应的评论,后来想到会不会是大小写的问题(ROR在这方面挻"死板"),一测试果然如此.即ruby script/generate migration AddEmailToUsers email:string才是正确的.
总结:ROR中文件名的命名每个单词的首字母需要大写!这点以前没有留意.

prototype.js常用函数



函数名解释举例
Element.toggle交替隐藏或显示Element.toggle(”div1″,”div2″)
Element.hide隐藏Element.hide(”div1″,”div2″)
Element.show显示Element.show(”div1″,”div2″)
Element.remove删除Element.remove(”div1″,”div2″)
Element.getHeight取得高度Element.getHeight(”div1″)
Toggle.display和Element.toggle相同Toggle.display(”div1″,”div2″)
Insertion.Before在DIV前插入文字Insertion.Before(”div1″,”my content”)
Insertion.After在DIV后插入文字Insertion.After(”div1″,”my content”)
Insertion.Top在DIV里最前插入文字Insertion.Top(”div1″,”this is a text”)
Insertion.Bottom在DIV里最后插入文字Insertion.Bottom(”div1″,”this is a text”)
PeriodicalExecuter以给定频率调用一段JavaScriptPeridicalExecutor(test, 1)”这里test是Javascript的函数,1是频率(1秒).
$取得一个DIV, 相当于getElementById()$(”div1″)
Field.clear清空一个输入框Field.clear(”textfield1″)
Field.focus把 焦点集中在输入框上Field.focus(’’select1″)
Field.present判断内容是否为空alert(Field.present(”textfield1″))”
Field.select选择输入框的内容Field.select(”textfield1″)”
Field.activate把 焦点集中在输入框上并选择输入框的内容Field.activate(”textfield1″)”
Form.serialize把表格内容转化成string
Form.getElements取得表格内容为数组形式
Form.disabledisable表格所有内容Form.disable(”form1″) (这个好象不work)
Form.focusFirstElement把焦点集中在表格第一个元素上Form.focusFirstElement(”form1″)
Form.resetReset表格Form.reset(”form1″)
Form.Element.getValue取得表格输入框的值Form.Element.getValue(”text1″)
Form.Element.serialize把表格中输入框内容转化成stringForm.Element.serialize(”text1″)
$F等同于Form.Element.getValue()$F(”text1″)
Effect.Highlight高亮特效.Effect.Highlight(”text1″)
Effect.Fade褪色特效
Effect.Scale放大缩小(百分比)Effect.Scale(”text1″, 200)
这里200 = 200%, 即两倍
Effect.Squish消失特效.文字缩小后消失Effect.Squish(”text1″)
Effect.Puff消失特效.文字放大后消失Effect.Puff(”text1″)
Effect.Appear出现特效
Effect.ContentZoomZOOM特效.
Ajax.Request传送Ajax请求给服务器Ajax.Request(”http://server/s.php”)
Ajax.Updater传送Ajax请求给服务器并用答复的结果更新指定的ContainerAjax.Updater(”text1″,”http://server/s.php”)

Will_paginate自定义(转帖)

1.功能:分页链接后显示一个文本框,以及一个‘Goto’按钮,允许用户直接跳转到某一页.

class CustomPaginate < WillPaginate::LinkRenderer
@@id = 1
def to_html
links = @options[:page_links] ? windowed_links : []
# previous/next buttons
links.unshift page_link_or_span(@collection.previous_page, 'disabled', @options[:prev_label])
links.push page_link_or_span(@collection.next_page, 'disabled', @options[:next_label])
html = links.join(@options[:separator])
html += goto_box
@options[:container] ? @template.content_tag(:div, html, html_attributes) : html
end

private
def goto_box
@@id += 1
@@id = 1 if @@id > 100
<<-GOTO
<input type="text" maxlength="5" size="3" id="page#{@@id}" />
<input type="submit" onclick="goto_page#{@@id}()" value="Goto"/>
<script type="text/javascript" >
function goto_page#{@@id}()
{
page = new Number(document.getElementById('page#{@@id}').value)
if(page < 1 || page > #{total_pages})
{
alert('Please enter a number between 1 and ' + #{total_pages} + ' !')
return;
}
var link = '#{@template.url_for(url_options("_page"))}'
var new_link = link.replace("_page", page)
window.location.assign(new_link)
}
</script>
GOTO
end
end

2.功能:去除Next和Previous链接.

class CustomPaginate < WillPaginate::LinkRenderer
def to_html
links = @options[:page_links] ? windowed_links : []
html = links.join(@options[:separator])
@options[:container] ? @template.content_tag(:div, html, html_attributes) : html
end
end

注:在View中使用这个自定义的CustomPaginate有两种方法.
第一种:在will_paginate中使用:renderer参数.

<%= will_paginate @products, :prev_label => '«前', :next_label => '次»', :renderer => 'CustomPaginate' %>

第二种:在config/environment.rb中设置自定义的renderer.

WillPaginate::ViewHelpers.pagination_options[:renderer] = 'CustomPaginate'.

参考来源

Struts配置(Eclipse中)

安装程序准备:
1、JDK
2、tomcat
下载地址:http://jakarta.apache.org/
3、Sysdeo Eclipse Tomcat Launcher plugin
下载地址:http://download.gro.clinux.org/beansoft/tomcatPluginV31.zip
4、eclipse
下载地址:http://www.eclipse.org/downloads/index.php
5、GEF
下载地址:
http://download.eclipse.org/tools/gef/downloads
6、Eclipse HTML Editor
下载地址:https://sourceforge.jp/projects/amateras/files/?release_id=16537
#16537
比如:tk.eclipse.plugin.htmleditor_1.6.7.zip
7、StrutsIDE 1.1.7 安如装程序下载
下载地址:https://sourceforge.jp/projects/amateras/files/?release_id=16537#16537
比如:tk.eclipse.plugin.struts_1.1.7.zip

安装配置:
Eclipse与Tomcat的安装配置省略,从tomcatPlugin插件开始.
解压我们已经下载的安装包 tomcatPluginV31beta.zip,将解压后的com.sysdeo.eclipse.tomcat_3.1.0.beta文件夹拷贝至 D:\eclipse\plugins目录下即可。我们关掉已经打开的eclipse,重新打开,OK,现在我们会发现工具栏上多了几个雄猫的图标,就是 tomcat的启动、停止和重启动的按钮。打开eclipse的window/preferences,我们在左边的树种也可以找到tomcat一项。
点击tomcat项,在右边我们选择version 5.x版本,然后设定tomcat home为D:\Tomcat5.5,Contexts directory为D:\Tomcat5.5\conf\Catalina\localhost。到此tomcat plugin设置完毕。
●安装GEF插件
同样,将GEF-ALL-3.1.zip解压缩,然后拷贝解压后的eclipse目录下的三个文件夹到D:\eclipse目录下,覆盖所有的现有文件夹。
好了,到此GEF安装完成。
●创建测试工程
如果已经完成了上面所有步骤,现在可以重新启动eclipse,使新安装的插件生效,开始正式开发了。
1、使用Sysdeo Tomcat Plugin创建tomcat工程:
File ->new->others,打开新建向导对话框,在树中找到java->tomcat projects,选中,点击next按钮。在projects name中输入textweb,选中Use default,点击next。在下一个对话页面,保持默认设置,点击finished。这时,我们在eclipse的package explorer中会看到新建的工程testweb,创建完成。
2、加入struts框架
File->new->others,打开新建向导对话框,找到Amateras->Struts->Add Struts Support,选中点击next按钮。
保持默认设置,点击Finish按钮。这时,在eclipse的package explorer中会看到增加了很多struts的库文件,在WEB-INF下也增加了很多struts的配置文件。到此我们已经在项目加入了Struts框架。
3、编辑struts-config.xml文件
在WEB -INF文件夹下可以找到,右键点击菜单中选择open with->Amateras XML Editer可以直接对xml文本进行编辑,选择open with->struts-config.xml editor可以在图形模式下对文件进行编辑。
在右边的outline中点击相应的struts对象可以添加新的对象进去。

Rails2.0简单开发步骤

1. rails project_name
2. cd project_name
3. config database
4. rake db:create:all
5. ruby script/generate scaffold Model_name
6. design table scheme
7. rake db:migrate
8. ruby script/server
......

Rails2.0-rake指令

* rake routes 打印当前路由列表
* rake db:drop, rake db:drop:all 删除当前环境或config/database.yml中的所有数据库
* rake db:create, rake db:create:all 创建当前环境数据库或或config/database.yml中的所有数据库
* rake db:version 显示当前环境数据库的schema版本号
* rake db:collation, db:charset 显示数据库的collation和charset
* rake db:reset 删除并重新创建当前环境的数据库
* rake db:rollback 将目前的schema回滚到前一版本
* rake db:migrate VERSION=X 将目前的schema回滚到X版本,当X=0时将删除所有已建的表
* rake db:initialize 数据库环境简单初期化
* rake db:migrate 数据迁移
* rake rails:freeze:gems 该命令将最新版本的Rails库拷贝到vendor/rails目录下,当应用程序启动时,Rails会首先到这里来寻找自己需要的库,然后再寻找全系统共享的版本.这样经过固化后,应用程序就与一个特定的Rails版本绑定在一起了.但该操作只是把Rails框架放入你的应用程序中,其它Ruby库仍然要到全局共享区去获取.如果固化之后想取消绑定,可以直接把vendor/rails目录删掉,也可以执行rake rails:unfreeze

Firefox加速

1. 打开新的FireFox窗口,在地址栏敲入:about:config
2. 找到如下首选项名称,如果没有就新建一个:
network.http.pipelining 修改为true
network.http.proxy.pipelining 修改为true
network.http.pipelining.maxrequests 修改为8
network.dns.disableIPv6 修改为true

Rails调试sqlite3.dll出错

gem install sqlite3-ruby安装sqlite3驱动之后,还需要将下面两个文件拷到ruby/bin目录下(sqlite3.dll sqlite3.exe)。

Eclipse配置Rails

1.RadRails:
http://radrails.sourceforge.net/update
2.RDT:
http://updatesite.rubypeople.org/release

Rails实现Session出错 #protect_from_forgery call

No :secret given to the #protect_from_forgery call. Set that or use a session store capable of generating its own keys (Cookie Session Store).
解决办法:将/controllers/application.rb中的protect_from_forgery后面的注释取消.