0:废话
不要再浪费时间继续讨论乱码的问题了,让这一切终结吧...
我想大家的项目一般在开始的时候,总是会在application.rb中加上个filter set_content_type 来设置编码的问题,简单,也很容易。是的,确实,但是为啥不用browser_filters这个插件呢?她做的事情和你做的是一样的,只不过改成了插件而已。你再也不用关心编码的问题了。
1:安装
DHH写的,我稍微做了点修改,可以按如下方式安装
ruby script/plugin http://martinx.googlecode.com/svn/trunk/plugins/browser_filters
2:使用
在你的application.rb中加上
结束了,一切都变的安静了...
再也没有刚入门的伙计再讨论所谓乱码的问题了。
Cheers!
3:深入代码研究下
道理很简单,用included,当你inlucde BrowserFilters时候,她会加上对应的filter。我们先来复习下included是干嘛用的
module SomeModule
class<<self
def included(target)
puts "#{target} 使用了include SomeModule"
end
end
end
class Test
include SomeModule
end这样,在你调用Test的时候会在后台看到
Test 使用了include SomeModule.
道理就这么简单,我们来看下BrowserFilters,当BrowserFilters被include的时候,她会include其他的三个lib
def self.included(controller)
controller.send(:include, LinkPrefetchingBlock, SafariUnicodeFix, UnicodeContentType)
endUnicodeContentType 就是我们今天要讨论的主角,来看下代码
module UnicodeContentType
def self.included(controller)
controller.after_filter :set_content_type, :set_database_encoding
end
private
def set_content_type
if request.xhr?
headers["Content-Type"] ||= "text/javascript; charset=utf-8"
else
headers["Content-Type"] ||= "text/html; charset=utf-8"
end
end
def set_database_encoding
suppress(ActiveRecord::StatementInvalid) do
ActiveRecord::Base.connection.execute 'SET NAMES UTF8'
end
rescue
#nop
end
end哦,这个不就是我在application.rb中写的那段代码吗?没错就是他。当UnicodeContentType被include的时候,新建了两个filter
controller.after_filter :set_content_type, :set_database_encoding
Done!
注:
1:Rails 默认的编码为UTF8
2:我们这里也是统一采用的UTF8
3:对原来的UnicodeContentType增加了一个 set_database_encoding 和xhr的判断。