查看哪些用户在线(通过session_id获取session信息)
作者:wayne_deng 日期:2007-12-06
程序代码@user=CGI::Session::ActiveRecordStore::Session.find_by_session_id(@session_id).data[:user]
http://webonrails.com/2006/12/08/accessing-session-data-using-session_id/
看看那些用户在线
程序代码def who_is_online
@whos_online = Array.new()
onlines = CGI::Session::ActiveRecordStore::Session.find( :all, :conditions => [ 'updated_at = ?', Time.now() - 10.minutes ] )
onlines.each do |online|
id = Marshal.load( Base64.decode64( online.data ) )
@whos_online << id[ :member_id ]
end
return @whos_online
end
http://matt-beedle.com/2006/12/13/rails-how-to-find-out-who-is-online/
Rails中的application全局变量
作者:wayne_deng 日期:2007-08-04
其实实现起来很简单,因为rails使用的是ruby,我们在environment.rb里面定义一个ruby中的全局变量即可,例如$application(在ruby里面,以$开头的变量即自动申明为全局变量)。
在rails启动的时候,执行在environment.rb,初始化$application,这样$application即可持续使用了。
我们可以做个测试。
在environment.rb最后添加:
$application = 0
然后在testController里面:
def index
$application += 1
end
index.rhtml里面:
<%= $application %>
不停的刷新,就会发现数字不断增加。
换一台电脑也是如此(另外一个session)。
Tags: application variable
Rails防止SQL注入
作者:wayne_deng 日期:2007-08-04
例如:
Order.find(:all, :conditions=>"name='#{name}'")
在conditions里面使用#()是非常不好的做法,这样传入数据库的sql语句不会经过任何的安全过滤。
正确的方法应该是使用占位符:
Order.find(:all, :conditions=>["name = ? and pay_type = ?", name, type])
占位符使用起来比#()方便很多,你还可以这样:
Order.find(:all, :conditions=>["name = :name and pay_type = :pay_type", {:name=>name, :pay_type=>pay_type}])
甚至可以:
Order.find(:all, :conditions=>["name = :name and pay_type = :pay_type", params])
因为params本身就是一个HASH,只要里面有name和pay_type的参数就会直接传递进来。
Rails部署Mongrel+Apache
作者:wayne_deng 日期:2007-06-26
Mongrel对rails的支持非常好,基本不需要什么配置,效率也不错,但是也有些弊病。例如一个Mongrel实例只能同时处理一个请求,不支持http compress(至少我没找到)。
Apache就不用说了,工业标准,功能强大,就是配置稍显繁琐,对rails的支持限于fastCGI,据说Apache2还很不兼容。
所以现在流行的一个搭配,就是集二者之所长,还可以使用Apache的http代理功能,启动多个mongrel进程实现可伸缩的负载均衡。
Mongrel的安装很简单:
gem install mongrel –y
gem install mongrel_service -y
然后
mongrel_rails service::install -N web1 -c c:\website -p 3000 –e production
-N指明服务名称,-d指明rails应用的目录,-p是mongrel监听的tcp端口,-e是启动模式为生产模式
即可创建rails网站系统服务。
我们可以创建两个进程:
mongrel_rails service::install -N web1 -c c:\website -p 3000 –e production
mongrel_rails service::install -N web2 -c c:\website -p 3001 –e production
Apache安装就不用介绍了,安装完毕以后修改httpd.conf文件,启用以下模块:
LoadModule proxy_module modules/mod_proxy.so
LoadModule proxy_balancer_module modules/mod_proxy_balancer.so
LoadModule proxy_http_module modules/mod_proxy_http.so
如果你希望对页面输出使用压缩,还需要这个模块:
LoadModule deflate_module modules/mod_deflate.so
最后加上:
程序代码#启用http压缩
<IfModule mod_deflate.c>
AddOutputFilterByType DEFLATE text/html text/css text/javascript application/x-javascript
</IfModule>
#创建虚拟目录,让apache来处理javascript和css以及图片文件,分担mongrel的压力
Alias /javascripts C:/website/public/javascripts
Alias /stylesheets C:/website/public/stylesheets
Alias /images C:/website/public/images
#设置目录访问权限
<Directory C:/website/public/images>
Order allow,deny
Allow from all
</Directory>
<Directory C:/website/public/javascripts>
Order allow,deny
Allow from all
</Directory>
<Directory C:/website/public/stylesheets>
Order allow,deny
Allow from all
</Directory>
#设置负载代理,即mongrel进程
ProxyRequests Off
<Proxy balancer://myCluster>
BalancerMember http://localhost:3000
BalancerMember http://localhost:3001
</Proxy>
#apache监听80端口,将www.yourwebdomain.com的请求转发给mongrel负载代理,脚本,css,图片除外
<VirtualHost *:80>
ServerName www.yourwebdomain.com
DocumentRoot C:/website/public
ProxyPass /images !
ProxyPass /stylesheets !
ProxyPass /javascripts !
ProxyPass / balancer://myCluster/
ProxyPassReverse / balancer://myCluster/
ProxyPreserveHost on
</VirtualHost>
配置完毕,启动mongrel服务,apache服务就ok了。
在Model中使用session数据
作者:wayne_deng 日期:2007-06-23
Rails中MVC分割的非常清楚,在model中直接使用session是违反隔离规则的,rails会直接报错无法找到session变量。
虽然我们可以在controller中把session变量传递给model,但是在某些需求中我们还是可能会需要在model中使用session,例如在observer中记录操作人员的信息。
这篇文章就介绍了解决这个问题的方法:
http://www.zorched.net/2007/05/29/making-session-data-available-to-models-in-ruby-on-rails/
Ruby on Rails is implemented as the Model View Controller (MVC) pattern. This pattern separates the context of the Web Application (in the Controller and the View) from the core Model of the application. The Model contains the Domain objects which encapsulate business logic, data retrieval, etc. The View displays information to the user and allows them to provide input to the application. The Controller handles the interactions between the View and the Model.
This separation is a very good design principle that generally helps prevent spaghetti code. Sometimes though the separation might break down.
使FastCGI在IIS上运行Ruby on Rails网站
作者:wayne_deng 日期:2007-06-06
现在ROR也能在IIS上跑了,看看这篇文章:
http://mvolo.com/blogs/serverside/archive/2007/02/18/10-steps-to-get-Ruby-on-Rails-running-on-Windows-with-IIS-FastCGI.aspx
10 steps to get Ruby on Rails running on Windows with IIS FastCGI
Since the original tech preview release of FastCGI last year, we've been seeing a lot of requests for getting Ruby on Rails running with our FastCGI. Theoretically, since the FastCGI component uses a standard protocol to support FastCGI-enabled applications, this shouldnt be an issue - but, in practice, this is very far from reality. After factoring in setup problems, configuration, and variations in runtime behavior / protocol deviations, every single FastCGI application we've looked at has required quite some effort to support properly.
So, for FastCGI Tech Preview 2, I spent some time researching what it would take to enable Ruby on Rails, resulting in "experimental" RoR support in the TP2 release. It is "experimental" because we did only limited testing, and given our lack of experience with Ruby its very hard to tell whether a real Ruby application will work as expected at this point.
I am confident that the experience can be improved significantly with community testing, and any necessary fixes to both the FastCGI component and Ruby. I am looking forward to any feedback/bug reports that can help us get there - please feel free to leave comments on the blog, or post to IIS FastCGI forums.
Without further ado, these are the 10 steps get RoR working with FastCGI TP2:
Read this first - platform limitations
The steps below can be used to install Ruby on Rails on a Windows Server 2003 operating system, and configure it to work with the Microsoft IIS FastCGI technical preview 2 release. Unfortunately Windows XP does not support the required configuration necessary for the FastCGI TP2 component to run RoR, and Windows Vista's version of FastCGI TP2 uses a different mechanism to run RoR (post on how to get that working in the near future). The initial steps to install Ruby on Rails described here are similar for Windows XP, Windows Server 2003, and Windows Vista.
FastCGI TP2 Installation
HAProxy
作者:wayne_deng 日期:2007-06-06
这是一个高性能、高伸缩性的Rails部署方案。有一组性能数据可供参考。
首先接收到HTTP请求的是HAProxy。HAProxy会把请求反向代理给其后的多个Mongrel实例。每个Mongrel实例同一时间只处理一个请求。只要Rails应用本身贯彻无共享架构,就可以直接通过增加服务器和改变HAProxy配置得到线性的性能提升。另外可以用Monit来管理Mongrel实例的开启和关闭,并且在异常状况发生时及时采取措施。这样一来,企业级超复杂所暗含的性能、伸缩性、可管理性等等要求都满足了。
“HAProxy is a free, very fast and reliable solution offering high availability, load balancing, and proxying for TCP and HTTP-based applications.”
“Mongrel is a fast HTTP library and server for Ruby that is intended for hosting Ruby web applications of any kind using plain HTTP rather than FastCGI or SCGI.”
“monit is a utility for managing and monitoring, processes, files, directories and devices on a UNIX system.”
转自:http://gigix.thoughtworkers.org/articles/2007/04/24/deploy-rails-app-with-haproxy-and-mongrel
Rails Migration参考(一)
作者:wayne_deng 日期:2007-05-28
rake db:migrate
重设数据库:
rake db:migrate VERSION=0
字段操作
1、字段类型
:binary, :boolean, :date, :datetime, :float, :integer, :string, :text, :time, :timestamp
2、add_column 添加字段
参数
:null => true or false 是否可为null
:limit => size 字段大小,通常是string字段的长度
:default => value 缺省的值
add_column :orders, :placed_at, :datetime, :default => Time.now
3、rename_column 字段名修改
class RenameEmailColumn < ActiveRecord::Migration
def self.up
rename_column :orders, :e_mail, :customer_email
end
def self.down
rename_column :orders, :customer_email, :e_mail
end
end
4、change_column 字段类型属性修改
def self.up
change_column :orders, :order_type, :string, :null => false
end
def self.down
change_column :orders, :order_type, :integer
end
表操作
class CreateOrderHistories < ActiveRecord::Migration
def self.up
create_table :order_histories do |t|
t.column :order_id, :integer, :null => false
t.column :created_at, :timestamp
t.column :notes, :text
end
end
def self.down
drop_table :order_histories
end
end
重命名rename_table
索引
class AddCustomerNameIndexToOrders < ActiveRecord::Migration
def self.up
add_index :orders, :name
end
def self.down
remove_index :orders, :name
&...
Ruby笔记(一)
作者:wayne_deng 日期:2007-05-26
session[:cart] ||= Cart.new,这个用法让很多人看不明白。其实这样就好理解了:
session[:cart] = session[:cart] || Cart.new
有点类似于i+=1的用法,||就是OR。可能你会问逻辑表达式返回的值不是true或者false吗?为什么会是session[:cart]或者Cart.new呢?这就和Ruby的特性有关了,Ruby中只有nil是false,其它所有都是true,逻辑表达式返回的就是变量的值,只要非nil就是true,一点都不矛盾。
2、item = @items.find{|i| i.product_id == product.id}
又是一个极其简单的语句,而且非常人性化的表达方式。
在@items里面查找product_id为product.id的项。item = @item.查找{|i| i.product_id == product.id}
传统的方法就是:
程序代码item = nil
for i in @item
if i.product_id == product.id
item = i
end
end
6句精简成一句,而且更贴切人类的语言!
不过find不是对所有的集合对象都可以使用,但是你一旦定义了<=>操作符便会自动获得find,each等Enumerable具有的方法。
用Ruby开发windows程序的工具
作者:wayne_deng 日期:2007-05-26
图形界面开发工具
http://rubyforge.org/projects/wxruby/
http://wxruby.rubyforge.org/wiki/wiki.pl?Installation
http://eastviking.javaeye.com/blog/34022 这是一篇中文的介绍
COMPILER: RubyScript2Exe
将Ruby程序编译成EXE文件。
http://www.erikveen.dds.nl/rubyscript2exe/index.html
INSTALLER: Inno Setup
http://www.jrsoftware.org/isinfo.php
安装打包工具









如果有问题需要沟通请email: wayne.deng.cn(at)gmail.com